在Swift中实现带动画的圆形进度视图

3

我希望对下面的圆形进度视图添加动画效果。动画应该从0开始,逐渐增加到我想要的数值。 但是我无法使动画正常工作。

func Popular(){
let circle = Pop;//Pop is a UIView

circle.bounds = CGRect(x: 0,y: 0, width: 100, height: 100);
circle.frame = CGRectMake(0,0, 100, 100);

circle.layoutIfNeeded()

var progressCircle = CAShapeLayer();

let centerPoint = CGPoint (x: circle.bounds.width / 2, y: circle.bounds.width / 2);
let circleRadius : CGFloat = circle.bounds.width / 2 * 0.83;

let circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true    );

progressCircle = CAShapeLayer ();
progressCircle.path = circlePath.CGPath;
progressCircle.strokeColor = UIColor.greenColor().CGColor;
progressCircle.fillColor = UIColor.clearColor().CGColor;

    UIView.animateWithDuration(3.0,
        delay: 1.0,
        options: [],
        animations: {
            progressCircle.lineWidth = 5.0;
            progressCircle.strokeStart = 0;
            progressCircle.strokeEnd = 0.20;

            circle.layer.addSublayer(progressCircle);

            circle

            progressCircle.strokeEnd = 0.2;

        },
        completion: { finished in
            print("Picutre done")


    })


}

你有收到任何错误信息吗?当你运行这个程序的时候会发生什么? - Arc676
完全没有错误信息... - Clarence
2个回答

9

使用 CABasicAnimation

    let circle = Pop

    var progressCircle = CAShapeLayer()

    let circlePath = UIBezierPath(ovalInRect: circle.bounds)

    progressCircle = CAShapeLayer ()
    progressCircle.path = circlePath.CGPath
    progressCircle.strokeColor = UIColor.greenColor().CGColor
    progressCircle.fillColor = UIColor.clearColor().CGColor
    progressCircle.lineWidth = 5.0

    circle.layer.addSublayer(progressCircle)


    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 0
    animation.toValue = 0.2
    animation.duration = 3
    animation.fillMode = kCAFillModeForwards
    animation.removedOnCompletion = false

    progressCircle.addAnimation(animation, forKey: "ani")

我有另一个问题,就是圆圈的大小是否总是大于视图。我该如何调整它? - Clarence
1
让circlePath = UIBezierPath(ovalInRect: CGRectInset(circle.bounds, 5 / 2.0, 5 / 2.0)) - PowHu

2

两件事 -

第一件 - 不要重新初始化progressCircle。你调用了progressCircle = CAShapeLayer ();两次。虽然这不是错误。

第二件 - 在开始动画之前添加子层。将circle.layer.addSublayer(progressCircle);移出动画块。


谢谢。我根据你的建议修改了代码,唯一的动画是进度圆突然出现了。我已经将代码放在了ViewDidAppear中。 - Clarence
是的。CABasicAnimation 是对子图层进行动画处理的正确方式。 - Abhinav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接