將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