Android Nine Patch Drawable Example

0

In this article, we will see how to create a Draw 9-patch bitmap to ensure that the image fit buttons of various sizes.

A Nine-Patch drawable graphic is a stretchable bitmap image, which Android will automatically re-size to accommodate the contents of the View in which you have placed it as the background.

A nine-patch is like any PNG image but contains an extra 1-pixel-wide border. It must be saved with the extension .9.png, and saved into the res/drawable/ directory of your project.

Android provides a tool to draw the nine-patch bitmap. You need to run the draw9patch command from your SDK sdk/tools directory to launch the Draw 9-patch tool.

Open the 9-patch tool

Draw 9-patch tool

Draw 9-patch tool

Next, open the png image.

Open png in draw-9-patch tool

Open png in draw-9-patch tool

As you can see, we have two panes, the left pane is your drawing area, in which you can edit the lines for the stretchable patches and content area. The right pane is the preview area.

Draw stretchable patches

Draw stretchable patches

Define the stretchable areas within the 1-pixel perimeter by drawing the lines that define the stretchable patches. In our image we just need three stretchable points. Click on the ‘Show patches’ to preview the stretchable patches in the drawing area. The pink is a stretchable patch.

Nine-Patch Image

Nine-Patch Image

For example, if we add one more stretchable point on the left side, lower corner, the image nicely moves to center of the button which is good but we also get an ugly shade in the bottom.

Nine-Patch image with an additional stretchable point

Nine-Patch image with an additional stretchable point

Click on ‘Show bad patches’ to make sure there are no bad patches. For example, if we include stretchable points that contains the person, you will see red borders around the patch areas complaining about that. You must eliminate them to make sure the stretched image will be coherent. You can see in the preview, the image messes up when it is stretched.

Bad Patch Example

Bad Patch Example

Select File > Save 9-patch. Your image will be automatically be saved with the .9.png file name.

Download the 9-patch images

This was an example about nine-patch images.

You can download the nine-patch images used here: nine-patch_images.zip
Share.

Comments are closed.