首页 > 解决方案 > CAShapeLayer 蒙版不显示

问题描述

我正在使用以下代码UIBezierPath制作面具:CAShapeLayer

- (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在调试器中查看,它看起来与我想要的完全一样。

标签: iosobjective-cuibezierpathcashapelayer

解决方案


使用layer.mask时,首先是要获取正确的路径。你不需要每次都移动到一个新的点。这样,您的路径由三个或四个无法闭合的子路径组成,以形成正确的路径。

第二个是尝试在View类本身中使用,而不是调用其他子视图,比如contentView。因为您可能不知道何时在子视图中调用它。在 UIView 子类中运行以下命令,例如在 UITableViewCell 中(从笔尖唤醒)。你能明白我的意思。如果你真的要使用 contentView,只要找到合适的位置放置你的 layer 代码。比如覆盖 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;

}

推荐阅读