【问题标题】:How to animate drawing shape fit in 60 second?如何在 60 秒内为绘图形状设置动画?
【发布时间】:2018-07-06 08:29:14
【问题描述】:

我是 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")
    }

【问题讨论】:

    标签: swift animation cashapelayer cabasicanimation


    【解决方案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 度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 2011-01-07
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多