Stretchable Images iOS7 Tutorial

A great way to reduce the size of images and reuse images is to use stretchable images. Smaller image sizes reduce the app size so users will have to wait less for the app to load in memory. In this tutorial we will stretch an image using Interface Builder and also programmatically. 

Open Xcode and create a new Single View Application. For product name, use iOS7StretchableImageTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices. 

In this tutorial we need an small image which we can stretch. Download the image here and add it to the project.  Go the Storyboard and drag two Image Views to the main view..The Storyboard should look like this.

First let's create our stretchable image in code. Select the Assistant Editor and open ViewController.m. Ctrl and drag from the top Image View to the @interface section and create the following outlet.

ImageView - Outlet.png

A stretchable image has 3 parts: A left cap, a one pixel stretchable area and a right cap.These images when scaled or resized will draw both caps on either side and repeat the middle pixel. Our image has a left and right cap of 5 pixels.

Change the viewDidLoad method to

- (void)viewDidLoad
[super viewDidLoad];

UIImage *roundedImage = [UIImage imageNamed:@"roundedimage"];
roundedImage = [roundedImage resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 5.0, 0.0, 5.0)];
self.myImageVIew.image = roundedImage;

We resize the image with the resizableImageWithCapInsets method of the UIImage class. Here we set the left and right inset values to 5.0, so the rounded corners are still in there original state and only the middle part of the image is stretched. Next we will stretch the bottom image using Interface Builder. Go tot the Storyboard and select the bottom Image View. Go to the Attributes Inspector and add the roundedimage.png file to the Image field. Change the Stretching Values to

StretchingValues - Attributes Inspector.png

The X value is set to 0.5 value, which is default by rounded corners. It means the top left and bottom left corners will not be stretched. Build and Run the project and you should see two identical stretched images.

Stretchable Image - Simulator.png

You can download the source code of the iOS7StretchableImageTutorial at the ioscreator repository on github.