Android 9 Patch images for custom controls

Given the high flexibility of interface controls in Android OS, where textviews can stretch to fit the screen or fit a given small area, designing a background for them can be problematic: a given image can fit the initial coordinates, but if the screen changes from portrait to landscape and the target control stretches, the aesthetics would be affected.
As a solution, we can design special images, called 9 patch images, that come with predefined “Stretching” areas that help keeping the same look. For an example, see the image to the left, where we have pairs of textviews+editviews in an attempt to create a labeled editview. The first pair is the default controls. Designing a background for them helps, but looks bad when the background image gets stretched, as for the pair number two. The last pair uses the same background, but made as a 9 patch image, and the appearance is as expected.

The 9 patch image is easy to make. First create your image as usual, it can have transparent areas as well. When ready, enlarge the image with 2 pixels on width and two on height, so you get a perimeter border of 1 pixel size. Use black and white to define areas that should not be stretched (white) and stretchable areas (black):

See the pictures above, they represent the editview background. You can see the corners are marked with white and the rest with black, so when stretching the corners will keep their aspect while the rectangular areas will stretch unaffected, and the aspect will be perfect . The second picture uses blue and red to highlight the stretchable area (red) and the non-stretchable area (blue).

Please note, that when saving a 9 patch file, you’ll need to place it in the resource folder and name it like this: filename.9.png . When using it you will refer to it as filename.

See this sample for a better understanding:

This article has 4 Comments

  1. Great job, Richard, thanks for providing those images. Hope you’ll find the time to make more.

  2. Radu,

    I have uploaded a few more packs, you will find the last one to be excellent IMO. I’m getting the hang of this slowly 🙂


Leave a Reply