Ellise
Ellise

Reputation: 81

How to set the contents of CAShapeLayer which has been shaped by UIBezierPath

I tried to add a mask layer on a UIImageView. This imageview hold an image and the mask layer hold another image by setting its contents. But when I add the mask layer onto the layer of imageview, the mask layer doesn't hold any image. The mask layer had been initialized by getter. The method adding mask layer is below:

- (void)circleButtonClicked{
    self.maskLayer.contents = (id)[UIImage imageNamed:@"mask.jpg"].CGImage;
    self.maskLayer.frame = CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_WIDTH);
    self.maskLayer.opacity = 0.5;

    [self.imageView.layer addSublayer:self.maskLayer];

    UIBezierPath * pPath = [UIBezierPath bezierPathWithArcCenter:self.imageView.center radius:(kSCREEN_WIDTH-100)/2 startAngle:0.0 endAngle:M_PI*2 clockwise:YES];
    self.maskLayer.path = pPath.CGPath;
    UIBezierPath * otherPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_WIDTH)];
    self.maskLayer.path = otherPath.CGPath;
    [otherPath appendPath:pPath];
    self.maskLayer.path = otherPath.CGPath;
    self.maskLayer.fillRule = kCAFillRuleEvenOdd;
} 

Upvotes: 2

Views: 406

Answers (1)

clemens
clemens

Reputation: 17722

Shape layers are used for displaying paths not images. There are three different ways to provide layer content (see Core Animation Programming Guide) but only one at a time.

There are some things in your code which I don't understand:

  1. Your maskLayer is just a normal layer and not a mask. When you want to use it as mask, you should use the mask property of CALayer and not add it as sublayer.
  2. Your layer should contain an image and a path, and should be a sublayer in an image view. I think its easier to use a image view and add it as subview to imageView.
  3. If you want to use an image as mask, which should be possible, you shouldn't use a JPEG image as source. Only the alpha values of a mask layer are considered, but the alpha values of the whole JPEG image are one. Thus, using a JPEG image is equivalent to using a filled square, or applying no mask.

Upvotes: 1

Related Questions