使用 CAKeyframeAnimation 反转 UIImageView 的旋转
Reverse the rotation of UIImageView using CAKeyframeAnimation
我正在使用以下代码无限旋转图像,旋转是顺时针的,但我还需要它每旋转 1-2 圈就逆时针反向旋转,然后再回到顺时针方向,如何让它工作?
/// Image Rotation - CAKeyframeAnimation
func rotate(imageView: UIImageView, rotationSpeed: Double) {
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.duration = rotationSpeed
animation.fillMode = CAMediaTimingFillMode.forwards
animation.repeatCount = .infinity
animation.values = [0, Double.pi/2, Double.pi, Double.pi*3/2, Double.pi*2]
/// Percentage of each key frame
let moments = [NSNumber(value: 0.0), NSNumber(value: 0.1),
NSNumber(value: 0.3), NSNumber(value: 0.8), NSNumber(value: 1.0)]
animation.keyTimes = moments
imageView.layer.add(animation, forKey: "rotate")
}
设置animation.autoreverses = true
,会反转一个动画。
逆时针旋转,可以这样做:
self.imageView?.transform = CGAffineTransform(rotationAngle: -2*CGFloat.pi)
我正在使用以下代码无限旋转图像,旋转是顺时针的,但我还需要它每旋转 1-2 圈就逆时针反向旋转,然后再回到顺时针方向,如何让它工作?
/// Image Rotation - CAKeyframeAnimation
func rotate(imageView: UIImageView, rotationSpeed: Double) {
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.duration = rotationSpeed
animation.fillMode = CAMediaTimingFillMode.forwards
animation.repeatCount = .infinity
animation.values = [0, Double.pi/2, Double.pi, Double.pi*3/2, Double.pi*2]
/// Percentage of each key frame
let moments = [NSNumber(value: 0.0), NSNumber(value: 0.1),
NSNumber(value: 0.3), NSNumber(value: 0.8), NSNumber(value: 1.0)]
animation.keyTimes = moments
imageView.layer.add(animation, forKey: "rotate")
}
设置animation.autoreverses = true
,会反转一个动画。
逆时针旋转,可以这样做:
self.imageView?.transform = CGAffineTransform(rotationAngle: -2*CGFloat.pi)