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

Cannot create two CGPathAddArc on the same CGMutablePathRef

我想明白为什么我只看到我的一个 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

结果:

有什么建议吗?谢谢!

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

    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)

这就是我得到的:

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

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

    lay.fillRule = kCAFillRuleEvenOdd

...我们得到这个:

如果我们引入遮罩元素...

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

...我们得到这个:

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

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

/* Note that using values very near 2π can be problematic. For example,
   setting `startAngle' to 0, `endAngle' to 2π, and `clockwise' to true will
   draw nothing. (It's easy to see this by considering, instead of 0 and 2π,
   the values ε and 2π - ε, where ε is very small.) Due to round-off error,
   however, it's possible that passing the value `2 * M_PI' to approximate
   2π will numerically equal to 2π + δ, for some small δ; this will cause a
   full circle to be drawn.

   If you want a full circle to be drawn clockwise, you should set
   `startAngle' to 2π, `endAngle' to 0, and `clockwise' to true. This avoids
   the instability problems discussed above. */

设置startAngle为0,endAngle为2π,clockwise为真 什么都不画。如果你想顺时针绘制一个完整的圆,你应该设置 startAngle 为 2π,endAngle 为 0,clockwise 为真。这样你就可以看到所有的圈子了。