如何在60秒内为绘图形状动画制作动画?

时间:2018-07-06 08:29:14

标签: swift animation cashapelayer cabasicanimation

我是Swift的新手,我没有太多的信息。我想创建动画时钟,并在时间间隔内填充“ CAShapeLayer ”路径,而不是尝试使用“ CABasicAnimation ”在60秒内。形状会在49秒内完成,动画完成会在60秒内完成,因此无法正常工作。比我更改了animation.byValue = 0.1,但结果是相同的。有人对这个问题有想法吗?

我的代码是:

    var startAngle = -CGFloat.pi / 2
    var endAngle = CGFloat.pi * 2
    var shapeLayer = CAShapeLayer()

    override func viewDidLoad() {
            super.viewDidLoad()

        let center = view.center
        let circlePath = UIBezierPath(arcCenter: center, radius: 100, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        shapeLayer.path = circlePath.cgPath
        shapeLayer.lineWidth = 20
        shapeLayer.strokeColor = UIColor.lightGray.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineCap = kCALineCapRound
        shapeLayer.strokeEnd = 0
        animate(layer: shapeLayer) //Animation func

            view.layer.addSublayer(shapeLayer)
    }

    private func animate(layer: CAShapeLayer) {
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.fromValue = 0.0
        animation.toValue = 1.0
        animation.duration = 60.0 //I think is counting by seconds?
        animation.repeatCount = .infinity
        animation.fillMode = kCAFillModeForwards
        layer.add(animation, forKey: "strokeEndAnimation")
    }

1 个答案:

答案 0 :(得分:1)

问题出在制作BezierPath上。

尝试以下方法:

let circlePath = UIBezierPath(arcCenter: .zero, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
    shapeLayer.path = circlePath.cgPath
    shapeLayer.lineWidth = 20
    shapeLayer.strokeColor = UIColor.lightGray.cgColor
    shapeLayer.strokeStart = 0
    shapeLayer.strokeEnd = 0
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.strokeEnd = 0
    shapeLayer.position = self.view.center
    shapeLayer.transform = CATransform3DRotate(CATransform3DIdentity, -CGFloat.pi / 2, 0, 0, 1)

arcCenter必须位于.zero并将形状的中心设置为视图的中心。不过,您的圈子将从最右边的点开始动画,因此添加CATransform可以将形状逆时针旋转90度。