Android 9 patch 图片(.9.png 格式图片)

  什么是.9.png格式的图片呢?为什么会有这个格式的图片?这种格式图片有哪些特殊的用途?请接着看...

定义:这种格式的图片在android 环境下具有自适应调节大小的能力,是一种为适应特殊拉申需要而产生的图片,防止图片在拉申后变形。

作用:(1)允许开发人员定义可扩展区域,当需要延伸图片以填充比图片本身更大区域时,可扩展区的内容被延展。(2)允许开发人员定义内容显示区,用于显示文字或其他内容

说明:

  有这样一张png图片:

  像这种图片我们一般作为背景图片来用,但在拉申的过程中会发生变形。我们不想让它在圆角及别的有特别形状的地方拉伸,因为拉伸这些地方会造成图片的变形。为了解决这个问题android中引入了一种新的图片格式.9.png。在android SDK 所带的tools里有一个制作这种格式图片的工具——draw9patch.bat。我们双击它就会打开一个如下图所示的工具:

说明:1)上方与左侧的黑点区所包含的区域就是拉伸区,当图片拉伸时只会拉伸这个区域的,别的区域不会被拉伸,左侧是三种拉伸情况下的预览图,可以看到图片没有变形。

   2)右侧与下方的黑线对应的区域为内容区,比如作为TextView,Button的背景时可能还需要显示文字。

   3)工具最左侧的蓝色区域是内容区的预览,文字会在这个区域内显示。

 实例说明:

有这样一个布局文件:

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     tools:context=".MainActivity" >
 6 
 7     <TextView
 8         android:id="@+id/t"
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:background="@drawable/t"
12         android:gravity="center"
13         android:text="@string/hello_world" />
14 
15     <TextView
16         android:id="@+id/tt"
17         android:layout_width="wrap_content"
18         android:layout_height="wrap_content"
19         android:layout_below="@id/t"
20         android:background="@drawable/tt"
21         android:gravity="center"
22         android:text="@string/hello_world" />
23 
24     <TextView
25         android:id="@+id/ttt"
26         android:layout_width="wrap_content"
27         android:layout_height="wrap_content"
28         android:layout_below="@id/tt"
29         android:background="@drawable/ttt"
30         android:gravity="center"
31         android:text="@string/hello_world" />
32     <TextView
33         android:layout_width="wrap_content"
34         android:layout_height="wrap_content"
35         android:layout_below="@id/ttt"
36         android:background="@drawable/tttt"
37         android:gravity="center"
38         android:text="@string/hello_world" />
39 
40 </RelativeLayout>

  说明:有四个TextView它们对应的背景分别为t.9.png,tt.9.png,ttt.9.png,tttt.png

在Graphial Layout下如下:

 分析:1)t.9.png设置了拉伸区、内容区,而且内容区适当大,我们可以看到这种显示效果刚好

   2)tt.9.png设置了与t.9.png相同的拉伸区,但内容区只用了两个像素设置

   3)ttt.9.png只设置了拉伸区

     4)tttt.png就是一个普通的png图片

大家可以结合4张图片对比一下4个TextView的显示情况。结论显而易见...

 PS:对于拉伸区在上方与左侧各用一个像素点设置就可以,而对于内容区(可选)就尽量大一些、尽量居中显示效果会更好。

原文地址:https://www.cnblogs.com/byghui/p/3045996.html