【问题标题】:Cannot create two CGPathAddArc on the same CGMutablePathRef不能在同一个 CGMutablePathRef 上创建两个 CGPathAddArc
【发布时间】:2016-03-17 01:32:23
【问题描述】:

我试图理解为什么我只看到我的一个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

结果:

有什么建议吗?谢谢!

【问题讨论】:

    标签: ios swift uibezierpath cgpath


    【解决方案1】:

    如果你按下命令键并点击 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 设置为true 将 什么都不画。如果你想顺时针画一个完整的圆,你应该设置 startAngle 为 2π,endAngle 为 0,clockwise 为真。这样你就可以看到所有的圈子了。

    【讨论】:

    • 哇,我从没想过它会与角度相关联,非常感谢!得到它的工作:)
    【解决方案2】:

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

        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
    

    ...我们得到这个:

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

    【讨论】:

    • 很棒的亚光。非常感谢!我会再次检查我的代码有什么问题而不是:)
    • 嘿,马特!我已经理解为什么它不起作用+为什么我无法重现您的代码,这与角度有关,正如您所说-代码很好,但是如果角度计算不正确,则会导致路径不被绘制。检查@gabbler 答案:) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2018-06-10
    相关资源
    最近更新 更多