## January 30, 2009

### iPhone: Rotate a UIImageView

Here's a simple little snippet that's useful if you want to rotate a UIImageView continuously for something like a clock hand graphic:
`#define DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) / 180.0 * M_PI)CGAffineTransform cgCTM = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(45));myImage.transform = cgCTM;`

1. Hi, do you know how to make the UIImageView rotate a random radian? Like if a user clicks a button, it makes the image rotate 45% or 90% or 25% at random? Thanks!

2. you could use the above code, but instead of hard-coding a number, you could use a function like the one below, that lets you use a randomly-generated number in between a high and low range:

float randRange(float low, float high)
{
float base=(random()%100)/100.0;
return base*(high-low)+low;
}

3. Ah, I see. Thanks for the response. Your website is very helpful in learning!

4. Hi,

I have tried the above code snippet and attached it to a button. My image however will only turn once and then it refuses to turn after that. What am I doing wrong?

5. if you give it a different number instead of 45, which is what the example shows, it will rotate to whatever angle you'd like.

6. Hi Justin....
Thanks a lot for the code snippet.. works beautifully :)

However, I did spot a small problem here. I'm looking to implement both image rotation AND zooming on a UIImageView. I noticed that if I try to zoom after I rotate using Affine transform, it gets screwed up bad..

I think the problem lies in the fact that affine transform rotates how the image looks on screen and not the actual image itself (the original image object will remain in the original position).

Any way of working around this?
Or is there any other way u know of doing image rotation?

7. I put this under the viewDidLoad method just to see if it would work and the image (a wheel) would turn continuously in my for loop, however it simply executes the first rotation and it does so prior to the image loading on the screen so should I make a separate method in order to physically see the image turn? And are for loops not applicable?

8. a for loop will not work - you would want to use an NSTimer, since this runs on a time-based interval, and updates the screen between "frames", as in Frames Per Second. for loops will complete before the screen is allowed to update, and before any other code is able to execute.

9. Hi Justin

I have used your code on an subclass of UIImageView which has been added as a subview.

When I rotate 90, 180, 270 degrees it works fine, but when I rotate some other angle the view screws and becomes rectangular instead of quadratic.

What am I doing wrong?

/Nicklas