在iOS中,笔划掩盖了CALayer

Ste*_*ord 12 objective-c ios quartz-core

我正在尝试使用一个圆角和一个笔划/边框创建一个标签(或任何其他视图).我可以使用以下代码实现前者:

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.label.bounds
                                      byRoundingCorners:UIRectCornerBottomRight
                                            cornerRadii:CGSizeMake(16.0f, 16.0f)];

CAShapeLayer *shape = [CAShapeLayer layer];
shape.frame = self.label.bounds;
shape.path = maskPath.CGPath;

self.label.layer.mask = shape;
Run Code Online (Sandbox Code Playgroud)

这适用于圆角,但使用以下代码不会按照我想要的方式应用笔划.相反,产生黑色(或任何backgroundColorself.label设置为)方形边框.

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.label.bounds
                                      byRoundingCorners:UIRectCornerBottomRight
                                            cornerRadii:CGSizeMake(16.0f, 16.0f)];

CAShapeLayer *shape = [CAShapeLayer layer];
shape.frame = self.label.bounds;
shape.path = maskPath.CGPath;

// Add stroke
shape.borderWidth = 1.0f;
shape.borderColor = [UIColor whiteColor].CGColor;

self.label.backgroundColor = [UIColor blackColor];
self.label.layer.mask = shape;
Run Code Online (Sandbox Code Playgroud)

关于如何在蒙版路径之后应用任意彩色笔划的任何建议?

Acc*_*yyc 36

你在形状层的正确轨道上.但是你应该有两个不同的层.首先是第一个示例中的遮罩层,它掩盖了您的视图(切断了您不希望看到的区域)

然后添加形状图层,但不作为遮罩层.另外,请确保不要使用borderWidth和borderColor,而是使用stroke.

//
// Create your mask first
//
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.label.bounds
                                      byRoundingCorners:UIRectCornerBottomRight
                                            cornerRadii:CGSizeMake(16.0f, 16.0f)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.label.bounds;
maskLayer.path = maskPath.CGPath;
self.label.layer.mask = maskLayer;    

//
// And then create the outline layer
//
CAShapeLayer *shape = [CAShapeLayer layer];
shape.frame = self.label.bounds;
shape.path = maskPath.CGPath;
shape.lineWidth = 3.0f;
shape.strokeColor = [UIColor whiteColor].CGColor;
shape.fillColor = [UIColor clearColor].CGColor;
[self.label.layer addSublayer:shape];
Run Code Online (Sandbox Code Playgroud)

请注意,笔触图层路径应位于蒙版路径的内部(小于).否则,描边路径将被掩模层掩盖.我已经将lineWith设置为3,这使得你可以看到宽度的一半(1.5 px),另一半将在掩模之外.

  • StrokeLayer覆盖标签,所以我添加了这个来修复`shape.fillColor = [UIColor clearColor] .CGColor` (8认同)