Thomas Denney

Nine patch images on iOS

Android developers will be familiar with the concept of nine-patch images: images that have a resizable central area but fixed width and height images. This is incredibly useful if you have a resizable button that you want to use a custom texture as the background, for example. This has always been available on iOS (and is fairly easy to roll out with custom CALayers too) however Xcode 5 has helped to make the process a lot easier.

To begin using ‘image slicing’ (Apple’s name for it - probably because you can have three-patch and nine-patch) you’ll firstly need to begin using asset catalogues - which provides a new easy way to manage images in your app and I highly recommend you migrate to using them. Once you’ve created a new image catalogue for your image file you can press the ‘show slicing’ button to begin dividing your image (you can have it resizable in one or two dimensions, with a choice of horizontal/vertical/both slicing).

Using the image is incredibly easy - if you’ve got a UIImageView you can simply set it using:


//Using with an image view
imageView.image = [UIImage imageNamed:@"myimage"];

//Using as the background to another view
//Note that you will need to redraw the background when resizing
//Therefore if you need to animate resizes it may be more sensible to add a UIImageView
//as the background to your view
UIImage * myImage = [UIImage imageNamed:@"myimage"];
UIGraphicsBeginImageContextWithOptions(myView.bounds.size, NO, 0);
[myImage drawInRect:myView.bounds];
UIImage * backgroundImage = UIGraphicsGetImageFromCurrentContext();
UIGraphicsEndImageContext();
myView.backgroundColor = [UIColor colorWithPatternImage:backgroundImage];

Unfortunately it seems a little illogical that you have to create a color from an image, but by drawing the image in a separate context it helps to ensure the image doesn’t become tiled.