Swift:UIBezierPath bezierPathByReversingPath()问题

时间:2016-01-29 00:50:26

标签: ios swift uibezierpath

我正在使用bezierPathByReversingPath()尝试制作动画圈。我终于找到了一个可以工作的方法,但是我正在将这个栏放到没有被删除的圈子中#34;。

守则:

@IBDesignable class circle: UIView {

    override func drawRect(rect: CGRect) {
        let center = CGPoint(x:bounds.width/2, y: bounds.height/2)

        let circlePath : UIBezierPath = UIBezierPath(arcCenter: center, radius:
            CGFloat(250), startAngle: CGFloat(0), endAngle: CGFloat(360), clockwise: true)
        let circlePath2 : UIBezierPath = UIBezierPath(arcCenter: center, radius:
            CGFloat(200), startAngle: CGFloat(0), endAngle: CGFloat(360), clockwise: true)

        circlePath.appendPath(circlePath2.bezierPathByReversingPath())
        circlePath.fill() //appendPath(circlePath.bezierPathByReversingPath())    
    }
}

图片

enter image description here

P.S。如果你想要一个我正在做的事情的例子,它是iOS游戏中的赢/输动画" Dulp"。

2 个答案:

答案 0 :(得分:1)

这是因为UIBezierPath(arcCenter: center, radius: CGFloat(250), startAngle: CGFloat(0), endAngle: CGFloat(360), clockwise: true)需要弧度,而不是你在此处指定的度数。

因此,人们需要以弧度为单位提供参数。

我创建了一个从度数转换为弧度的简单函数;结果很好。

这是功能:

func degreesToRadians(degree : Int) -> CGFloat
{
    return CGFloat(degree) * CGFloat(M_PI) / 180.0
}

用法:

let circlePath : UIBezierPath = UIBezierPath(arcCenter: center, radius: 250.0, startAngle: self.degreesToRadians(0), endAngle:    
                                             self.degreesToRadians(360), clockwise: true)

let circlePath2 : UIBezierPath = UIBezierPath(arcCenter: center, radius: 200.0, startAngle: self.degreesToRadians(0), endAngle:        
                                              self.degreesToRadians(360), clockwise: true)

或者可以创建协议扩展名:

extension Double
{
    var degreesToRad : CGFloat
    {
        return CGFloat(self) * CGFloat(M_PI) / 180.0
    }
}

用法:

let circlePath : UIBezierPath = UIBezierPath(arcCenter: center, radius: 250.0, startAngle: 0.0.degreesToRad , endAngle: 360.0.degreesToRad, clockwise: true)

let circlePath2 : UIBezierPath = UIBezierPath(arcCenter: center, radius: 200.0, startAngle: 0.0.degreesToRad, endAngle: 360.0.degreesToRad, clockwise: true)

答案 1 :(得分:1)

首先,角度是弧度 - 而不是度数。所以你的圈子大约要走30次左右,而不是在他们开始的地方结束。是什么给了你吧。

其次,你可以划一个圆而不是创建两个并填充它们:

@IBDesignable class Circle: UIView {
  override func drawRect(rect: CGRect) {
    let center = CGPoint(x:bounds.width/2, y: bounds.height/2)

    let circlePath : UIBezierPath = UIBezierPath(arcCenter: center, radius:
      CGFloat(225), startAngle: CGFloat(0), endAngle: CGFloat(2*M_PI), clockwise: true)
    circlePath.lineWidth = 50
    circlePath.stroke()
  }
}