使用CAShapeLayer作为CAShapeLayer的遮罩时的薄边框

问题描述:

在Swift中,我有两个半透明圆圈,它们都是CAShapeLayer。由于他们是半透明的,它们之间没有任何重叠,像这样变得可见:使用CAShapeLayer作为CAShapeLayer的遮罩时的薄边框

enter image description here

相反,我希望他们能在视觉上“合并”在一起。我试过的解决方案是使用圆圈2作为圆圈1的掩码,因此切掉重叠。

这个解决方案通常工作,但我得到的圈2的外细线:

enter image description here

我的问题:我怎样才能在右边圆圈摆脱薄,外线?为什么它在那里?


的代码如下(Xcode playground can be found here):

private let yPosition: CGFloat = 200 
    private let circle1Position: CGFloat = 30 
    private let circle2Position: CGFloat = 150 
    private let circleDiameter: CGFloat = 200 
    private var circleRadius: CGFloat { return self.circleDiameter/2.0 } 

    override func loadView() { 
     let view = UIView() 
     view.backgroundColor = .black 

     self.view = view 

     let circle1Path = UIBezierPath(
      roundedRect: CGRect(
       x: circle1Position, 
       y: yPosition, 
       width: circleDiameter, 
       height: circleDiameter), 
      cornerRadius: self.circleDiameter) 

     let circle2Path = UIBezierPath(
      roundedRect: CGRect(
       x: circle2Position, 
       y: yPosition, 
       width: circleDiameter, 
       height: circleDiameter), 
      cornerRadius: self.circleDiameter) 

     let circle1Layer = CAShapeLayer() 
     circle1Layer.path = circle1Path.cgPath 
     circle1Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor 

     let circle2Layer = CAShapeLayer() 
     circle2Layer.path = circle2Path.cgPath 
     circle2Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor 

     self.view.layer.addSublayer(circle1Layer) 
     self.view.layer.addSublayer(circle2Layer) 

     //Create a mask from the surrounding rectangle of circle1, and 
     //then cut out where it overlaps circle2 
     let maskPath = UIBezierPath(rect: CGRect(x: circle1Position, y: yPosition, width: circleDiameter, height: circleDiameter)) 
     maskPath.append(circle2Path) 
     maskPath.usesEvenOddFillRule = true 
     maskPath.lineWidth = 0 

     let maskLayer = CAShapeLayer() 
     maskLayer.path = maskPath.cgPath 
     maskLayer.fillColor = UIColor.black.cgColor 
     maskLayer.fillRule = kCAFillRuleEvenOdd 

     circle1Layer.mask = maskLayer 
    } 
+0

细线几乎可以肯定抗锯齿 –

+0

我有同样的想法 - 任何方式来控制在这种情况下的别名? – BlackWolf

+0

这并不直接回答你的问题,但你可以使用两个弧来绘制上面的形状,而不是试图合并两个圆。 – Sparky

如果两个CAShapeLayers具有相同的阿尔法值,你可以将它们放在一个新的父的CALayer然后设置父的alpha,而不是内部。