Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the rotation of UIImageView using CAKeyframeAnimation

I'm using the following code to rotate an image infinitely, the rotation is clockwise but I also need it to reverse rotation to counter clockwise every 1-2 rotations and then back to clockwise, how to get this to work?

    /// 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")
}
like image 344
Jessica Kimble Avatar asked Nov 06 '22 14:11

Jessica Kimble


1 Answers

Set animation.autoreverses = true, will reverse an animation.

like image 81
Sagar Chauhan Avatar answered Nov 14 '22 23:11

Sagar Chauhan