17.5. Constructing Resizable Images

Problem

You want to be able to save some memory and disk space by creating resizable images for your UI components. You may also want to be able to create different sizes of the same UI component, such as a button, using only a single background image.

Note

Resizable images refer to simple PNG or JPG images that can be loaded into an instance of UIImage.

Solution

Create a resizable image using the resizableImageWithCapInsets: instance method of the UIImage class.

Discussion

Resizable images may sound a bit strange at first, but they make sense when you understand the different display needs of your app. For instance, you may be working on an iOS app where you want to provide a background image for your buttons. The bigger the text in the button, the wider the button. So you now have two options on how you want to provide the background images of your buttons:

  • Create one image per size of button. This will add to the size of your bundle, consumes more memory, and requires much more work from you. In addition, any change to the text requires a new image to make the button fit.

  • Create one resizable image and use that throughout the app for all the buttons.

Without a doubt, the second option is much more appealing. So what are resizable images? They are simply images that are divided into two virtual areas:

  • An area that will not be stretched.

  • An area that will be stretched to fit any size.

As you can see in Figure 17-16, we have created an image for a button. ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.