iPhone Developer Tips Stats:
|
Rotate an Image with Animation – Part 1
Editor’s Note: Part 2 of this post shows how rotate an images, buttons and other UI objects up to 360 degrees as well as rotating objects clockwise or counter-clockwise.
Last week I wrote a tip to demonstrate how to move an image on screen using animation. In this post I’ll show how to rotate an image with animation. One thing to cover as it relates to rotation is conversion of degrees to radians. Although most of us think in terms of degrees when it comes to rotating objects, the libraries we’ll access require rotation to be specified in radians.
Radians and Degrees
A circle is 360 degrees, which translates to 2Π radians. Thus, to convert from degrees to radians, we’ll need these definitions:
// This is defined in Math.h #define M_PI 3.14159265358979323846264338327950288 /* pi */ // Our conversion definition #define DEGREES_TO_RADIANS(angle) ((angle / 180.0) * M_PI)
Follow this link to read more about the relationship between degrees and radians.
Method To Rotate an Image
The rotateImage method takes four parameters – the image to rotate, duration of the animation in seconds, the animation curve to apply, and the degrees to rotate. Here is how the method looks:
- (void)rotateImage:(UIImageView *)image duration:(NSTimeInterval)duration curve:(int)curve degrees:(CGFloat)degrees { // Setup the animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:duration]; [UIView setAnimationCurve:curve]; [UIView setAnimationBeginsFromCurrentState:YES]; // The transform matrix CGAffineTransform transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees)); image.transform = transform; // Commit the changes [UIView commitAnimations]; }
Calling the Rotate Method
First thing to note is that a positive value for the degrees will rotate clockwise – a negative will rotate counter-clockwise. Calling the rotate method is as simple as shown below:
- (void)startApp { UIImageView *imageToMove = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ArrowUp.png"]]; imageToMove.frame = CGRectMake(10, 10, 20, 100); [self.view addSubview:imageToMove]; [self rotateImage:imageToMove duration:3.0 curve:UIViewAnimationCurveEaseIn degrees:180]; ... }









I seem to be having trouble with this code. When I call rotateImage:…. and I use 360 degrees it doesn’t move at all. Shouldn’t it spin in a full circle? And when I put 270 degress it spins -90. How can I make it so the image spins in a full circle twice?
Joe,
I posted a question on the iPhone Dev Tips Google Group: How to rotate an image 360 degrees?
Fabrizio posted a nice working code example.