4

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")
}
Dharman
  • 21,838
  • 18
  • 57
  • 107
Jessica Kimble
  • 301
  • 3
  • 13
  • Have a look on this https://stackoverflow.com/questions/9468707/ios-cakeyframeanimation-rotationmode-on-uiimageview – Abhishek Sep 05 '19 at 13:54

2 Answers2

1

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

Sagar Chauhan
  • 5,115
  • 2
  • 17
  • 48
0

for counter clockwise rotation, you can do this:

self.imageView?.transform = CGAffineTransform(rotationAngle: -2*CGFloat.pi)
Frankenxtein
  • 386
  • 2
  • 16