Image Views
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];
Code Listing 4.8 Creating an image view.
Note that initWithImage: automatically adjusts the frame of the new image view to match the width and height of the image assigned (Figure 4.12).
Figure 4.12 The image displaying a graphic.
If you resize the image view, you can see that the image automatically scales to fit (Figure 4.13):
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];
Figure 4.13 Resizing the 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;
Figure 4.14 shows 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.
Figure 4.14 Resizing the image view while maintaining its aspect ratio.
Animating images
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.
- 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 setAnimationRepeatCount:0];
- To begin the animation, add the following:
[myImageView startAnimating];
- To stop the animation, you call stopAnimating.