我正在尝试创建一个带有圆角和描边/边框的标签(或与此相关的任何其他 View )。我可以使用以下代码实现前者:
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;
这对圆角非常有效,但使用以下代码并没有按照我想要的方式应用笔触。而是生成黑色(或 self.label
的 backgroundColor
设置为)方形 边框。
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;
关于如何应用遵循屏蔽路径的任意彩色笔划有什么建议吗?
最佳答案
您在形状层的正确轨道上。但是你应该有两个不同的层。首先是第一个示例中的 mask 层,它 mask 了您的 View (切断了您不想看到的区域)
然后你也添加形状层,但不是作为 mask 层。另外,确保不使用 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];
请注意,您的描边层路径应位于(小于) mask 路径内。否则,描边路径将被 mask 层遮盖掉。我已将 lineWith 设置为 3,这样您就可以看到一半的宽度 (1.5 px),而另一半将在 mask 之外。
关于ios - iOS 中的描边蒙版 CALayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357132/