Creating & Using 9-patch images in Android

The SDK and Android Studio both ship with the “Draw 9-patch” tool (“draw9patch” in the SDK tools folder) which is a simple editor. Here is a nicer one which is also open source. It has a simple but clever default image.

The official documentation has improved over the years. In summary, nine patch images’ most important advantage is that they can specify (non-contiguous) areas to scale:

A NinePatch graphic is a standard PNG image that includes an extra
1-pixel border. It must be saved with the 9.png extension in the
res/drawable/ directory of your project.

Use the border to define the stretchable and static areas of the
image. You indicate a stretchable section by drawing one (or more)
1-pixel wide black line(s) in the left and top part of the border (the
other border pixels should be fully transparent or white). You can
have as many stretchable sections as you want. The relative size of
the stretchable sections stays the same, so the largest section always
remains the largest.

You can also define an optional drawable section of the image
(effectively, the padding lines) by drawing a line on the right and a
line on the bottom. If a View object sets the NinePatch graphic as its
background and then specifies the view’s text, it stretches itself so
that all the text occupies only the area designated by the right and
bottom lines (if included). If the padding lines aren’t included,
Android uses the left and top lines to define this drawable area.

Diagram of the border parts of a 9-patch image

But the docs lack good examples. This tutorial has some great examples at the end that answer the second part of your question, explaining how the scaling works – not just for buttons – but also frames, and it has a complete example project that you can download and play with.

Leave a Comment