Android: 9-patch resources

The most powerful tool when preparing graphics for Android is 9patch. But many people have problems understanding it, so let me try to clarify it.

9patch is essentially an image that can be stretched without distorting it. A typical example is a rounded rectangle (a typical contemporary button), where you don’t want the corners to be distorted by scaling and only want the middle parts to be stretched.

It’s not only that 9patch will get rid of the blurriness, it also locks the padding and dimensions when stretching. Notice how the non-9patch stretched image is indented and blurry.

With 9patch you define a 3×3 grid over the image. Android uses the grid to slice the image into nine parts. The four corner parts are kept, while the middle ones are scaled:

9patch is a standard PNG file that includes 1-pixel-wide transparent border. In the border, we mark the stretchable area by black pixels in the left and top lines of the border:

The image has to be saved with a .9.png extension so Android can tell it’s a 9patch image.

Apart from marking the slices, you can also specify the padding that will be used for content (i.e., an icon or button label). The padding is adjusted when 9patch is stretched so the distances from the edges are kept the same.

Similarly to the slices, the padding is marked in the right and bottom lines of the 1-pixel-wide border by black pixels. If you omit it, Android will use the left and top markers.

With the way 9patch works, you can tell that it won’t be useful for everything. Textures or patterns are the source of most of the problems. Take a look at these examples:

The only way to handle these situations is to either not take the textures into account, or to just create a static image for every size required by the application.

Don’t forget that the 9patch resource is still just an image and that it should be also prepared for the densities.