Rotate an Image or Button with Animation – Part 2
February 1, 2010
In a previous post Rotate an Image with Animation – Part 1 I wrote a short code block using CGAffineTransform to rotate an image. Problem is, if you want to rotate an image 360 degrees, or repeat a rotation a specified number of times, you’ll need to take a different approach, which is the focus of this post. This code example will use a layer for animation so this same effect can used on images, buttons, etc.
The video below shows a rotating a button (on the left) as well as image. Notice the direction of rotation is clockwise on the button and counter-clockwise on the image. Also, notice that the rate of the spin is different for each object.
Spin/Rotate Code
This method accepts a layer object (CALayer), the duration of the spin (in seconds) and the direction:
- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration direction:(int)direction { CABasicAnimation* rotationAnimation; // Rotate about the z axis rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; // Rotate 360 degress, in direction specified rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * direction]; // Perform the rotation over this many seconds rotationAnimation.duration = inDuration; // Set the pacing of the animation rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; // Add animation to the layer and make it so [inLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; } |
Calling the spinLayer Method
The code below shows how to call the method, specifying the duration and the direction. Make note that the layer associated with the image/button is passed in to the method:
#define SPIN_CLOCK_WISE 1 #define SPIN_COUNTERCLOCK_WISE -1 UIImageView *testImage; ... [self spinLayer:testImage.layer duration:1 direction:SPIN_CLOCK_WISE]; UIButton *infoButton; ... [self spinLayer:infoButton.layer duration:3 direction:SPIN_COUNTERCLOCK_WISE]; |
Spin Effect – Timing Functions
Notice in the original example I specified kCAMediaTimingFunctionEaseInEaseOut as the timing function name, which defines the pacing of the animation, in this case, the animation begins slowly, accelerates and then slows again.
You can experiment with the following timing functions for various effects:
kCAMediaTimingFunctionLinear
kCAMediaTimingFunctionEaseIn
kCAMediaTimingFunctionEaseOut
kCAMediaTimingFunctionEaseInEaseOut
kCAMediaTimingFunctionDefault



