Friday 12 August 2011

Android 9 Patch Scaled PNG Image Guide

About 9 Patch PNG Images 

9 patch scalable graphics are PNG based images that have 9 areas, called patches, that scale separately. This is handy for mobile devices that have smaller screens with differing resolutions and aspect ratios. The Android SDK comes with a utility called draw9patch to create 9 patch images from PNG files. The draw9patch utility is located in the tools/ directory of the SDK.

The easiest way to think of a 9 patch image is to lay a tic-tac-toe board over the image. The grid from the tic-tac-toe board can then be moved across the image to fit the correct scaling zones. The 4 corner scaling zones don't scale. These are fixed size blocks. The top and bottom center column blocks only scale horizontally. The left and right edge boxes on row 2 only scale vertically. Finally the center scales both vertically and horizontally.

Creating 9 Patch Images

This is the image we're going to work with. 

Right click on the image and save it. Next launch draw9patch from the tools directory of the SDK and open the image. The left pane of draw9patch shows the images and allows you to set the patch boundaries. To the right is a preview pane that shows the results of the defined patches. To set a patch boundary click along the edge of the image. Clicking on the top or bottom will create a vertical patch boundary. Clicking on the left or right will create a horizontal patch boundary. Right click to remove a patch boundary.
Setup the image so that the colored bars create an even border around the image. Download patched example here.
This allows for the creation of custom button and other graphic elements that can be scaled and re-sized minimizing the amount of work to keep a consistent look and feel across multiple devices.

Basic application use

Layout

To include a 9 patch image via a layout use an ImageView

<ImageView 
  android:id="@+id/test_image"
  android:src="@drawable/test_9patch_patched"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  />

Insert this ImageView component into res/layout/main.xml below the TextView. For the code it's just as with any other Android image. Create an ImageView to work with
package higherpass.Test9Patch;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class Test9Patch extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView patch = (ImageView) findViewById(R.id.test_image);
    }
}

 

 



1 comment:

  1. Plenty of 9 patch PNGS can be found here for free:
    http://android9patch.blogspot.com/

    Enjoy!

    Richard.

    ReplyDelete