ios - iOS 中的描边蒙版 CALayer

标签 ios objective-c quartz-core

我正在尝试创建一个带有圆角和描边/边框的标签(或与此相关的任何其他 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.labelbackgroundColor 设置为)方形 边框。

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/

相关文章:

iphone - 如何比较 char* 和 NSString?

iOS 绘制弧线未按预期工作

ios - UIViewController didRotateFromInterfaceOrientation : not being called

cocoa - 使用 OS X NSColorspace 切换颜色同步配置文件

ios - 在 iOS 的 iPad 上将图像捏合到最左角?

iphone - 访问 Android 和 iOS 平台的数据/语音流

ios - super initWIthCoder 返回父类型?

iOS:关于 GLKMatrix4MakeLookAt 结果中的相机信息的问题

ios - Firebase 深层链接 Web URL 查询为空 - iOS

iphone - 如何在 info.plist 中动态传递 Facebook App ID?