Android: Resizable background images with 9 patch

September 26th, 2011

One concern when developing for Android devices is supporting the various screens that are available. Android does a fairly good job with this, by allowing various drawable directories for particular screens, and allowing layout configurations using density-independent pixel (dp) instructions. There is good information at developer.android.com regarding tips and best practices for supporting various screen sizes.

Another consideration for supporting multiple screen sizes is to use 9 patch png images as backgrounds for buttons and application content. Using 9 patch png images for backgrounds can help address both screen size issues as well as orientation concerns. You can use Google’s Draw 9 patch tool, or any graphics tool to generate these images. 9 patch creates sections within your image that can be maintained (corners), and areas to be repeated or stretched over x and y. It is simple to create 9 patch images, and it makes a huge difference in presentation.

Below are a couple of extreme examples, but even with less extreme scenarios, a user can generally spot a resized image that lost its proportionality. 9 patch removes these issues, and avoids the necessity to include different background images for each screen size, button dimension, background area, etc. Both examples use a similar 46×42 pixel image as their background. However, the 9 patch version includes an extra 1 pixel border that delineates how the background image should grow and what border area should be maintained. This information allows the corners to stay consistent for different proportions, and the edges to remain a consistent thickness no matter how large we want the area to be.

Without 9 patch

With 9 patch

Nicholas Whittier

Nicholas is a developer who loves to figure out how things work. Whether it is an errant bash script, missing kernel drivers, CSS conflicts, a JRE incompatibility, an unsolved Rubik's cube, or anything in between, he wants to learn why it is broken and how to fix it. Additionally, Nicholas fancies GNU/Linux system administration, database administration, Java development, and web development.