如何使图像旋转(动画)
How to make image spin (animation)
我有一张正方形图片,我知道如何让它旋转。但不确定如何让它像这里的动画一样旋转:
注意它是如何旋转的……然后稍微停下来……然后再次旋转……等等。
我只有一个基本的旋转但看起来不像上面的 gif:
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 3) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2)
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
关于如何完成的任何想法?
需要用到加减速的计时函数,也就是ease-in-ease-out计时函数。
我已修改您的函数以使用 Core Animation 的标准缓入缓出计时函数:
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 0.8) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let radians = CGFloat.pi / 4
rotateAnimation.fromValue = radians
rotateAnimation.toValue = radians + .pi
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
结果:
请注意,在您的图像中,方框似乎每 180 度暂停一次,因此我已将功能更改为仅旋转 180 度。由于这个盒子是90度径向对称的,所以看起来还是绕了一圈,在180度和360度处有停顿。
如果您需要为没有任何径向对称的图像设置动画,则需要使用 CAKeyframeAnimation
来实现 180 度和 360 度的缓入缓出效果。
用 delay
.
的重复动画也可以达到类似的效果
UIView.animate(withDuration: 1,
delay: 0.2,
options: [.repeat],
animations: { imageView.transform = imageView.transform.rotated(by: CGFloat.pi) },
completion: nil)
我有一张正方形图片,我知道如何让它旋转。但不确定如何让它像这里的动画一样旋转:
注意它是如何旋转的……然后稍微停下来……然后再次旋转……等等。
我只有一个基本的旋转但看起来不像上面的 gif:
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 3) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2)
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
关于如何完成的任何想法?
需要用到加减速的计时函数,也就是ease-in-ease-out计时函数。
我已修改您的函数以使用 Core Animation 的标准缓入缓出计时函数:
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 0.8) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let radians = CGFloat.pi / 4
rotateAnimation.fromValue = radians
rotateAnimation.toValue = radians + .pi
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
结果:
请注意,在您的图像中,方框似乎每 180 度暂停一次,因此我已将功能更改为仅旋转 180 度。由于这个盒子是90度径向对称的,所以看起来还是绕了一圈,在180度和360度处有停顿。
如果您需要为没有任何径向对称的图像设置动画,则需要使用 CAKeyframeAnimation
来实现 180 度和 360 度的缓入缓出效果。
用 delay
.
UIView.animate(withDuration: 1,
delay: 0.2,
options: [.repeat],
animations: { imageView.transform = imageView.transform.rotated(by: CGFloat.pi) },
completion: nil)