Building Android Application introduced me to 9-patch image format. While studying it, I feel 9 patch is poorly documented. After using it for sometimes, I can understand why 9patch is so powerful for building a nice Android UI. In this writing, I will introduce 9patch image and how 9patch works.
Nine patch is basically png image file. However, it has special properties that make it very good for scalable image. To differentiate from ordinary png, the file name of nine patch image has extra “.9” string after its name, for example “beautiful_button.9.png”. Nine patch is not firstly used in Android, it is also used in Web Design using CSS .
As its name suggest, 9 patch is composed of 9 parts. Each part is separated by a guide which can be found in the outer most part of 9patch image. The guide is a straight black line (RGB #000000) with exactly 1 pixel wide.
There are two separate nine-slices in 9-patch image. The first 9 slices determine its scalable property. These slices are separated by top and left guide (see image below). Area 2 and 8 determine area that will be stretched if 9 patch image is scaled horizontally. Area 4 and 6 determine area that will be stretched if it is scaled vertically. Area 5 is stretched if the image is scaled either vertically or horizontally. And area 1,3,7 and 9 will maintain its size even when 9 patch image is scaled.
The second 9 slices determine fill property of 9 patch image. These slices are separated by guide located at right and bottom of image. The most important area is area 5, which will enclose the content of of your image. The other slices will act as border.
Nine patch acts nicely if it is scaled up, however it is not so good in scaling down. Thus, when generating 9patch image, it is better to start from the smallest size while maintaining image style.