---
title: "转载 android可拉伸图片处理(.9.png)格式的图片"
author: "ableouou"
date: "2011-04-06T16:00:00Z"
tags: []
categories: ["移动开发"]
slug: "android-9-png"
draft: false
lastmod: "2011-04-06T16:08:34Z"
id: 987644
url: "https://ableouou.iteye.com/blog/987644"
---

NinePatchDrawable 绘画的是一个可以伸缩的位图图像，Android会自动调整大小来容纳显示的内容。一个例子就是NinePatch为背景，使用标准的Android按钮，按钮必须伸缩来容纳长度变化的字符
NinePatchDrawable是一个标准的PNG图像，它包括额外的1个像素的边界，你必须保存它后缀为.9.png,并且保持到工程的res/drawable目录中。如果你是从APK解压后得到的*.9.png文件,注意它是已将周围的空白像素去掉了的，在使用时必须再加上。

这个边界是用来确定图像的可伸缩和静态区域。你可以在左边和上边的线上画一个或多个黑色的1个像素指出可伸缩的部分（你可以需要很多可伸缩部分），它的相对位置在可伸缩部分相同，所以大的部分总是很大的。

你还有可以在图像的右边和下边画一条可选的drawable区域（有效的，内边距线）。如果你的视图对象设置NinePath为背景然后指定特殊的视图字体，它将自行伸缩使所有的文本来适应根据右线与底部线设计好的区域（如果有的话），当然内边距线不包括其中，Android可以使用左边的线与上面的线来定义一个drawable区域。

我们来澄清一下这两条不同的线，左边跟顶部的线来定义哪些图像的像素允许在伸缩时被复制。底部与右边的线用来定义一个相对位置内的图像，视图的内容就放入其中。



可以使用tools\draw9patch.bat工具来编辑*.9.png图片，可以看出该工具非常直观的展示了图片在上下或左右拉伸时的效果以及作为背景时其内容显示的位置。



作Nine Patch为按钮背景使用方法：

<Button id="@+id/big"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="text!"
        android:textSize="30sp"
        android:background="@drawable/my_button_background"/>
如果想要设置按钮在按下或者获得焦点时，有不同的背景图片，则可以将需要的背景图片放在drawable目录下（.9.png）格式，同时在drawable目录中新建一个xml文件（内容如下），android:background="@drawable/（XML文件名）"，这样就可以在不同状态显示不同的背景。
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="true"
       android:drawable="@drawable/button_focused" />
    <item android:state_focused="false" android:state_pressed="true"
       android:drawable="@drawable/button_focused" />
    <item android:state_focused="true"
       android:drawable="@drawable/button_focused" />
    <item android:state_focused="false"
       android:drawable="@drawable/button_defocused" />
</selector>

作者：Feisky 
出处：http://www.cnblogs.com/feisky/ 
http://www.cnblogs.com/feisky/archive/2010/01/16/1649502.html