无法在同一CGMutablePathRef上创建两个CGPathAddArc

时间:2016-03-17 01:32:24

标签: ios swift uibezierpath cgpath

我试图理解为什么我只看到我的一个CGPathAddArc

代码:

  var r: CGRect = self.myView.bounds
 var lay: CAShapeLayer = CAShapeLayer()
        var path: CGMutablePathRef = CGPathCreateMutable()
        CGPathAddArc(path, nil, 30, 30, 30, 0, (360 * CGFloat(M_PI))/180, true    )
        CGPathAddArc(path, nil, 70, 30, 30, 0, (360 * CGFloat(M_PI))/180, true    )

        CGPathAddRect(path, nil, r2)
 CGPathAddRect(path, nil, r)
        lay.path = path
        lay.fillRule = kCAFillRuleEvenOdd
        self.myView.layer.mask = lay

结果:

enter image description here

有什么建议吗?谢谢!

2 个答案:

答案 0 :(得分:1)

您需要做的是 debug 。怎么样?好吧,如果有疑问,你的第一步应该是简化。在这种情况下,您应该首先在掩码和填充规则的上下文之外测试代码。当你这样做时,你会发现弧线实际上都存在。我运行了这个简化版的代码:

    let lay = CAShapeLayer()
    lay.frame = CGRectMake(20,20,400,400)
    let path = CGPathCreateMutable()
    CGPathAddArc(path, nil, 30, 30, 30, 0, 
        (360 * CGFloat(M_PI))/180, true)
    CGPathAddArc(path, nil, 70, 30, 30, 0, 
        (360 * CGFloat(M_PI))/180, true)
    lay.path = path
    self.view.layer.addSublayer(lay)

这就是我得到的:

enter image description here

如您所见,两个弧都存在。所以你的结果必然是由于弧线绘制之外的一些复杂因素。

如果我们添加填充规则......

    lay.fillRule = kCAFillRuleEvenOdd

......我们得到了这个:

enter image description here

如果我们引入掩码元素......

    // self.view.layer.addSublayer(lay)
    self.view.layer.mask = lay

......我们得到了这个:

enter image description here

因此,使用基本测试,您应该能够让自己相信代码的这一部分。您现在可以引入越来越多的实际代码,直到您开始获得不良结果,然后您就会知道导致问题的原因。

答案 1 :(得分:1)

如果您按下命令键并单击CGPathAddArc函数,您将看到文档。

startAngle

endAngle设置为0,将clockwise设置为2π,将startAngle设置为true将 什么都没画。如果要按顺时针方向绘制整圆,则应设置        endAngle到2π,clockwise到0,{{1}}为true。这样你就可以看到所有圈子。