CAShapeLayer遮罩未显示

时间:2018-09-30 02:32:21

标签: ios objective-c uibezierpath cashapelayer

我正在使用UIBezierPathCAShapeLayer和以下代码制作蒙版:

- (void)createPath {
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(100, 100)];
    [path moveToPoint:CGPointMake(100, 100)];
    [path addLineToPoint:CGPointMake(0, 100)];
    [path moveToPoint:CGPointMake(0, 100)];
    [path addLineToPoint:CGPointMake(0, 0)];
    [path closePath];

    CAShapeLayer *layer = [CAShapeLayer new];
    layer.frame = self.contentView.bounds;
    layer.path = path.CGPath;
    self.contentView.layer.mask = layer;
}

但我的contentView并没有掩盖,而是完全消失了。我尝试在调试器中查看path,它看起来完全符合我的期望。

1 个答案:

答案 0 :(得分:1)

使用layer.mask时,首先是获得正确的路径。您无需每次都移动到新的位置。通过这种方式,您的路径由三个或四个子路径组成,这些子路径无法闭合以形成正确的路径。

第二个尝试在View类本身中使用,而不是调用其他子视图,例如contentView。因为您可能不知道何时在子视图中调用它。在UIView子类中运行以下内容,例如在UITableViewCell中(从笔尖唤醒)。可以理解我的意思。如果您确实要使用contentView,只需找到放置图层代码的正确位置即可。例如覆盖setNeedLayout等。

 - (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
[self createPath];
}


 - (void)createPath {   
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(100, 100)];
 //  [path moveToPoint:CGPointMake(100, 100)];
[path addLineToPoint:CGPointMake(0, 100)];
 //  [path moveToPoint:CGPointMake(0, 100)];
[path addLineToPoint:CGPointMake(0, 0)];
[path closePath];


CAShapeLayer *layer = [CAShapeLayer new];
layer.frame = self.contentView.bounds;
layer.path = path.CGPath;
self.layer.mask  = layer;  // not self.contentView.layer.mask;

}