动画在Swift中绘制一个饼形

时间:2016-08-29 18:33:42

标签: ios swift core-animation

我试图在代码中设置一个“馅饼”圆圈形状,以一个完整的圆圈开始,然后以一个空圆圈结束,每一步都可以平滑地动画出一块“馅饼”,像这样:

Pie One

Pie Two

我创建了这样的形状:

func drawOval() {

    let newOvalPath = UIBezierPath()
    let ovalRect = CGRect(x: 0, y: 0, width: 100, height: 100)

    newOvalPath.addArcWithCenter(CGPoint(x: ovalRect.midX, y: ovalRect.midY), radius: ovalRect.width / 2, startAngle: -10 * CGFloat(M_PI)/180, endAngle: -90 * CGFloat(M_PI)/180, clockwise: true)
    newOvalPath.addLineToPoint(CGPoint(x: ovalRect.midX, y: ovalRect.midY))
    newOvalPath.closePath()

    MyStyleKit.instance.ovalPath = newOvalPath

}

...

import UIKit

class MyStyleKit {
static let instance = MyStyleKit()

private var _ovalPath: UIBezierPath?

var ovalPath: UIBezierPath? {
    get {
        return _ovalPath
    } set {
        _ovalPath = newValue
    }
}

func drawCircle() {

    let color = UIColor(red: 0.930, green: 0.043, blue: 0.043, alpha: 1.000)

    if let ovalPath = self.ovalPath {

        color.setFill()
        ovalPath.fill()
    }
}

然后我尝试根据NSTimer设置转换动画,并且每秒都会调用此函数:

func updateOval() {

    startAngle += 30

    let newOvalPath = UIBezierPath()
    let ovalRect = CGRect(x: 0, y: 0, width: 100, height: 100)

    newOvalPath.addArcWithCenter(CGPoint(x: ovalRect.midX, y: ovalRect.midY), radius: ovalRect.width / 2, startAngle: startAngle * CGFloat(M_PI)/180, endAngle: -90 * CGFloat(M_PI)/180, clockwise: true)
    newOvalPath.addLineToPoint(CGPoint(x: ovalRect.midX, y: ovalRect.midY))
    newOvalPath.closePath()

    MyStyleKit.instance.ovalPath = newOvalPath
    MyStyleKit.instance.drawCircle()
    self.drawView.setNeedsDisplay()

}

问题是圆圈没有动画,它只是从一个角度突然变化到下一个角度。如何从一个位置平滑地动画到下一个位置?

1 个答案:

答案 0 :(得分:-1)

正如我所见,您每秒将角度更改30度。这就是为什么您无法获得流畅的动画的原因。尝试每毫秒将视图刷新1/30度,您会获得更加流畅的动画