中风屏蔽了iOS中的CALayer

我试图创build一个标签(或任何其他视图)与一个圆angular和一个笔画/边框。 我可以用以下代码实现前者:

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; 

这对圆angular很好,但使用下面的代码不会按照我想要的方式应用笔画。 取而代之的是生成一个黑色(或者任何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; 

关于如何应用遮罩后的任意颜色描边的任何build议?

你正处于形状层的正确轨道上。 但是你应该有两个不同的层次。 首先在第一个例子中掩盖你的视图的遮罩层(切掉你不想被看见的区域)

然后你也添加形状图层,但不能作为遮罩层。 另外,请确保不要使用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]; 

请注意,您的中风层path应位于内部(小于)掩码的path。 否则,描边path将被遮罩层掩盖。 我已经把lineWith设置为3,这样就可以看到宽度的一半(1.5px),而另一半将会在mask之外。

如果您CALayer ,则可以使用所需的掩码来实例化它,还可以覆盖layoutSubLayers以在该掩码中包含所需的边框。

可以做这个几个方法。 在Ill下面,通过使用给定掩码的path ,并将其分配给要用于在layoutSubLayers构造新边框的class属性。 有可能这个方法可以被多次调用,所以我也设置了一个布尔值来跟踪这个。 (也可以将边框分配为类属性,每次删除/重新添加。现在,我使用布尔检查。

Swift 3:

 class CustomLayer: CALayer { private var path: CGPath? private var borderSet: Bool = false init(maskLayer: CAShapeLayer) { super.init() self.path = maskLayer.path self.frame = maskLayer.frame self.bounds = maskLayer.bounds self.mask = maskLayer } override func layoutSublayers() { let newBorder = CAShapeLayer() newBorder.lineWidth = 12 newBorder.path = self.path newBorder.strokeColor = UIColor.black.cgColor newBorder.fillColor = nil if(!borderSet) { self.addSublayer(newBorder) self.borderSet = true } } required override init(layer: Any) { super.init(layer: layer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }