使用CAShapeLayer作为CAShapeLayer的掩码时的细边框

时间:2017-09-14 19:49:26

标签: ios swift core-animation calayer cashapelayer

在Swift中,我有两个半透明的圆圈,两个都是CAShapeLayer。由于它们是半透明的,因此它们之间的任何重叠都是可见的:

enter image description here

相反,我希望他们在视觉上和#34;合并"一起。我尝试的解决方案是使用圆圈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
    }

1 个答案:

答案 0 :(得分:0)

如果两个CAShapeLayers具有相同的alpha值,您可以将它们放在新的父CALayer中,然后设置父级的alpha。