如何设置被UIBezierPath整形的CAShapeLayer的内容
How to set the contents of CAShapeLayer which has been shaped by UIBezierPath
我试图在 UIImageView 上添加遮罩层。这个图像视图保存一个图像,遮罩层通过设置它的内容来保存另一个图像。但是当我将遮罩层添加到图像视图层时,遮罩层不包含任何图像。遮罩层已由 getter 初始化。添加遮罩层的方法如下:
- (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;
}
形状图层用于显示路径而非图像。提供图层内容的方式有三种(参见 Core Animation Programming Guide),但一次只能使用一种方式。
您的代码中有些地方我不明白:
- 您的
maskLayer
只是一个普通图层,不是蒙版。当你想用它作为遮罩时,你应该使用 CALayer
的 mask
属性 而不是将它添加为子图层。
- 您的层应该包含图像和路径,并且应该是图像视图中的子层。我认为使用图像视图并将其作为子视图添加到
imageView
. 更容易
- 如果您想使用图像作为蒙版(这应该是可能的),则不应使用 JPEG 图像作为源。仅考虑遮罩层的 alpha 值,但整个 JPEG 图像的 alpha 值是一个。因此,使用 JPEG 图像等同于使用填充正方形,或者不应用蒙版。
我试图在 UIImageView 上添加遮罩层。这个图像视图保存一个图像,遮罩层通过设置它的内容来保存另一个图像。但是当我将遮罩层添加到图像视图层时,遮罩层不包含任何图像。遮罩层已由 getter 初始化。添加遮罩层的方法如下:
- (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;
}
形状图层用于显示路径而非图像。提供图层内容的方式有三种(参见 Core Animation Programming Guide),但一次只能使用一种方式。
您的代码中有些地方我不明白:
- 您的
maskLayer
只是一个普通图层,不是蒙版。当你想用它作为遮罩时,你应该使用CALayer
的mask
属性 而不是将它添加为子图层。 - 您的层应该包含图像和路径,并且应该是图像视图中的子层。我认为使用图像视图并将其作为子视图添加到
imageView
. 更容易
- 如果您想使用图像作为蒙版(这应该是可能的),则不应使用 JPEG 图像作为源。仅考虑遮罩层的 alpha 值,但整个 JPEG 图像的 alpha 值是一个。因此,使用 JPEG 图像等同于使用填充正方形,或者不应用蒙版。