If I create a CAShapeLayer with just a background color it shows up, but if i set the content to an image, nothing shows.
CAShapeLayer* leftDot = [CAShapeLayer layer];
leftDot.opacity = 1.0;
leftDot.frame = CGRectMake(leftRef.CGPointValue.x, leftRef.CGPointValue.y, 2 * radius, 2 * radius);
leftDot.position = CGPointMake(leftRef.CGPointValue.x + 4, leftRef.CGPointValue.y + 4);
leftDot.cornerRadius = radius;
[leftDot setContents:[UIImage imageNamed: @"glow.png"]];
[self.layer addSublayer: leftDot];
You have to set the CGImage for the layer
CAShapeLayer doesn't work that way. You would create a normal CALayer with the image as its content and then use the shape layer as the mask of that layer to achieve the effect you are after.
You can get the image to appear by setting the
fillColor
rather than thecontents
:[NOTE: updated to Swift 2.2 and Swift 3]
Quick answer: use CALayer
As explained in CAShapeLayer Class Reference, a
CAShapeLayer
is used for drawing shapes using a custom path. Setting an image as itscontents
will simply be ignored.If you just want to show an image in a layer (let's suppose your file is named
image.png
), you can use aCALayer
and set itscontents
property so that it references theCGImage
representation of your image:Swift 2.2:
Swift 3:
Longer answer: keep using CAShapeLayer
Since the OP asked specifically about
CAShapeLayer
, the question may read like "How can I crop an image into a specific shape usingCAShapeLayer
?"There are two solutions I'd suggest you try:
1) Masking
Create a normal
CALayer
and set the image as itscontents
. Then create aCAShapeLayer
with the path you like and use it as the first layer'smask
.Swift 2.2:
Swift 3:
Don't forget to set the right frames and paths, and you should be able to achieve the effect you wanted.
2) Fill color
Create a
CAShapeLayer
with the path you like, then use your image as itsfillColor
.Swift 2.2:
Swift 3:
You may find this approach easier at first, but controlling the way the image fills your shape is not trivial at all.