The UIImageView class extends UIView to provide support for displaying images. Its default initializer, initWithImage:, takes a UIImage as its only parameter (Code Listing 4.8):
UIImage *anImage = [UIImage imageNamed:@"myImage.png"]; UIImageView *myImageView = [[UIImageView alloc] initWithImage:anImage];
Note that initWithImage: automatically adjusts the frame of the new image view to match the width and height of the image assigned .
If you resize the image view, you can see that the image automatically scales to fit :
CGSize viewSize = myImageView.bounds.size; //shrink width 50% viewSize.width = viewSize.width * 0.5; //keep height the same viewSize.height = viewSize.height; CGRect newFrame = CGRectMake (0,0,viewSize.width, viewSize.height); [myImageView setFrame:newFrame];
Code Listing 4.8 Creating an image view.
You can control scaling behavior by the contentMode property of UIView, which defaults to UIViewContentModeScaleToFill.
For example, to maintain the aspect ratio of the image, you would write this:
myImageView.contentMode = UIViewContentModeScaleAspectFit;
In the resulting image, note that although the image itself is scaled, the image view still has the same bounds . Any part of the bounds not rendered in the image will be transparent.
UIImageView lets you animate over an array of images, which is handy for creating progress animations. Code Listing 4.9 shows the code updated to animate over three images.
Code Listing 4.9 Animating over an array of images.
To animate over an image:
- Create the image view, and set its frame:
CGRect viewFrame = CGRectMake (0,0,200,200); UIImageView *myImageView = [[UIImageView alloc] initWithFrame:viewFrame];
- Create and set the image array:
NSArray *arrImages = [[NSArray alloc] initWithObjects: [UIImage imageNamed: @"apple.png"], [UIImage imageNamed: @"apple2.png"], [UIImage imageNamed: @"apple3.png"],nil]; [myImageView setAnimationImages:arrImages]; [arrImages release];
- You can control the speed of the animation (in seconds) and number of times the animation is repeated. The default is 0, making the animation loop indefinitely:
[myImageView setAnimationDuration:0.5]; [myImageView setAnimation RepeatCount:0];
- To begin the animation, add the following:
- To stop the animation, you call stopAnimating.