【问题标题】:Strange issue in animating drawing a circle in Swift在 Swift 中绘制圆形动画的奇怪问题
【发布时间】:2017-10-21 13:02:20
【问题描述】:

我正在尝试用动画绘制一个圆圈:

func drawProgressCircle(with endAngle: CGFloat) {
    let progressBezierPath = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.width / 2), radius: self.frame.width / 2.5, startAngle: -CGFloat(Double.pi / 2), endAngle: endAngle, clockwise: true)
    let progressShapeLayer = CAShapeLayer()
    progressShapeLayer.path = progressBezierPath.cgPath

    progressShapeLayer.strokeColor = UIColor.brown.cgColor
    progressShapeLayer.fillColor = UIColor.clear.cgColor
    progressShapeLayer.lineWidth = 15.0

    // Do not draw initially. Wait for animation
    progressShapeLayer.strokeEnd = 0.0

    // Make corners rounded
    progressShapeLayer.lineCap = kCALineCapRound

    self.layer.addSublayer(progressShapeLayer)
    self.animate(circleWith: progressShapeLayer, from: -CGFloat(Double.pi / 2), to: endAngle, with: 2.0)
}

为了给它设置动画,我调用了这个函数:

func animate(circleWith shapeLayer: CAShapeLayer, from: CGFloat, to: CGFloat, with duration: TimeInterval) {
    // We want to animate the strokeEnd property of the circleLayer
    let animation = CABasicAnimation(keyPath: "strokeEnd")

    // Set the animation duration appropriately
    animation.duration = duration

    // Animate from start point to end point
    animation.fromValue = from
    animation.toValue = to

    // Do a linear animation (i.e. the speed of the animation stays the same)
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

    // Set the circleLayer's strokeEnd property to 1.0 now so that it's the
    // right value when the animation ends.
    shapeLayer.strokeEnd = 1.0

    // Do the actual animation
    shapeLayer.add(animation, forKey: "animate")
}

但我不知道为什么它没有动画。画布是空的,在 2 秒后它就出现在画布上。没有任何动画。

有什么问题?为什么它没有动画绘图?

【问题讨论】:

    标签: ios swift animation uibezierpath cashapelayer


    【解决方案1】:

    将动画 formValue 和 toValue 替换为:

    // Animate from start point to end point
    animation.fromValue = 0
    animation.toValue = 1
    

    基本上,keyPath strokeCABasicAnimation 不知道你在画一个圆,它只是从 0 到 1 动画。 如果你给 toValue 一个 0.5 的值,它只会动画到路径的一半。

    这与 keyPath 的 CABasicAnimation position 不同,后者将 CGPoint 用于 fromValuetoValue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多