将repeatcount设置为1,并在每个动画停止后重新添加动画。我不确定这是否会导致性能问题,因为我使用非常基本的方形视图进行测试。
通过添加CAMediaTimingFunction
参数,你可以控制是否使用kCAMediaTimingFunctionLinear
- 为那些正常的动画循环,或者使用一个自定义,如kCAMediaTimingFunctionEaseIn
- 为关键帧动画显示的平滑过渡。
// your function to start the acceleration
@IBAction func buttonTapped(_ sender: UIButton) {
accel = true
speed = 2.0
timeOffset = self.rect.layer.convertTime(CACurrentMediaTime(), from: nil)
timeOffset = timeOffset - lastStart
// memorize the timeoffset, new speed (2x) and a boolean flag
self.rect.layer.removeAllAnimations()
}
// delegate - memorize the CFTimeInterval
func animationDidStart(_ anim: CAAnimation) {
lastStart = self.rect.layer.convertTime(CACurrentMediaTime(), from: nil)
}
// delegate - start a new loop of animation each time it's stopped
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if accel {
accel = false
let opt = CAMediaTimingFunction(controlPoints: 0.5, 0.2, 0.9, 0.7)
rotateAnimation(theView: rect, speed: speed, fromValue: CGFloat(.pi * 2.0 * Float(timeOffset)/10.0), toValue: CGFloat(.pi * 2.0 * Float(timeOffset)/10.0 + .pi * 2.0), option: opt)
} else {
rotateAnimation(theView: rect, speed: speed, fromValue: CGFloat(.pi * 2.0 * Float(timeOffset)/10.0), toValue: CGFloat(.pi * 2.0 * Float(timeOffset)/10.0 + .pi * 2.0))
// note that timeOffset is initialize to be 0.
}
}
你想在这里自定义CAMediaTimingFunction,通过0.5的斜率开始,逐渐增加至1.0,我这里没有优化的贝塞尔曲线,你可以做自己想要的曲线。
最后一个小调整到您的动画功能:
func rotateAnimation(theView: UIView, speed: Float, duration: CFTimeInterval = 10.0, fromValue: CGFloat = CGFloat(0.0), toValue: CGFloat = CGFloat(.pi * 2.0), option: CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = fromValue
rotateAnimation.toValue = toValue
rotateAnimation.duration = duration
rotateAnimation.speed = speed
rotateAnimation.repeatCount = 1
rotateAnimation.delegate = self
rotateAnimation.timingFunction = option
theView.layer.add(rotateAnimation, forKey: nil)
}
没有改变持续时间的帮助? – 3stud1ant3
@ 3stud1ant3不会,它会改变速度,但几秒钟后动画会恢复到原来的速度。 – NoKey
在改变持续时间的同一个音符上,你是否尝试过一段时间循环,条件行指定了动画的最终位置? – ProgrammingEnthusiast