I was surprised to find out how few samples there were for adding and manipulating images in an iPhone app. Rotating an image seemed to be tricky to figure out, but the code for adding and rotating an image is very simple.
The code below shows how to:
- Create a UIImage with an image file
- Create a UIImageView with the dimensions of the UIImage
- Add the UIImage to the UIImageView using the image property
- Add the UIImage to the View
- Create a CGAffineTransform CGAffineTransformMakeRotation
- Apply the CGAffineTransformMakeRotation to the UIImageView
UIImage *image = [UIImage imageNamed:@"image.png"]; UIImageView *imageView = [ [ UIImageView alloc ] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ]; imageView.image = image; [self addSubview:imageView]; CGAffineTransform rotate = CGAffineTransformMakeRotation( 1.0 / 180.0 * 3.14 ); [imageView setTransform:rotate];
The referenced “image.png” needs to be dragged into the Resources folder of your project inside Xcode. This action will prompt you to confirm the copying of the file to the project folder.
To make the image continue to rotate, include the latter two transform lines inside a loop, perhaps dependent on the device’s acceleration.
If you’ve got a better, more efficient way of doing the above, please feel free to comment.