Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 23  XML Drawables


Why are they called 9-patches? A 9-patch breaks your image into a three-by-three grid – a grid with
nine sections, or patches. The corners of the grid remain unscaled, the sides are only scaled in one
dimension, and the center is scaled in both dimensions, as shown in Figure 23.9.


Figure 23.9  How a 9-patch scales


A 9-patch image is like a regular PNG image in everything except two aspects: Its filename ends with
.9.png, and it has an additional one-pixel border around the edge. This border is used to specify the
location of the center square of the 9-patch. Border pixels are drawn black to indicate the center and
transparent to indicate the edges.


You can create a 9-patch using any image editor, with the draw9patch tool provided as part of the
Android SDK, or using Android Studio.


First, convert your two new background images to 9-patch images by right-clicking on
ic_button_beat_box_default.png in the project tool window and selecting Refactor → Rename... to
rename the file to ic_button_beat_box_default.9.png. (If Android Studio warns you that a resource
with the same name already exists, click Continue.) Then, repeat the process to rename the pressed
version to ic_button_beat_box_pressed.9.png.


Next, double-click on the default image in the project tool window to open it in Android Studio’s built-
in 9-patch editor, as shown in Figure 23.10. (If Android Studio does not open the editor, try closing the
file and collapsing your drawable folder in the project tool window. Then re-open the default image.)

Free download pdf