作者:郭孝星
微博:郭孝星的新浪微博
博客:http://blog.csdn.net/allenwells
Github:https://github.com/AllenWells
【Android应用开发技术:用户界面】章节列表
9Patch图片是一种特殊的PNG图片,该图片以.9.png为后缀名,它在原始图片四周各添加一个宽度为1像素的线条,这4条线决定了该图片的缩放规则和内容显示格则。
一 9Patch图片的显示规则
9Patch图片left边和top边的直线共同决定了图片的缩放区域,以左边直线为左边界绘制矩形,它覆盖的区域可以纵向缩放,以上面直线为上边界绘制矩形,它覆盖的区域可以水平缩放,它们二者的交集可以在两个方向上缩放。
9Patch图片right边和bottom边的直线共同决定了图片内容的显示区域,以右边直接为右边界绘制矩形,以下边直线绘制矩形,它们两者的交集就是图片内容的显示区域。
这4条线把图片分成9个部分,因此称为.9.png
二 9Patch图片的制作方法
Android提供了制作9Patch图片的drew9patch.bat工具,在Android SDK安装路径的tools目录下,该文件内容如下所示:
@echo off
rem Copyright (C) 2008 The Android Open Source Project
rem
rem Licensed under the Apache License, Version 2.0 (the "License");
rem you may not use this file except in compliance with the License.
rem You may obtain a copy of the License at
rem
rem http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
rem don‘t modify the caller‘s environment
setlocal
rem Set up prog to be the path of this script, including following symlinks,
rem and set up progdir to be the fully-qualified pathname of its directory.
set prog=%~f0
rem Change current directory and drive to where the script is, to avoid
rem issues with directories containing whitespaces.
cd /d %~dp0
rem Check we have a valid Java.exe in the path.
set java_exe=
call lib\find_java.bat
if not defined java_exe goto :EOF
set jarfile=draw9patch.jar
set frameworkdir=.
set libdir=
if exist %frameworkdir%\%jarfile% goto JarFileOk
set frameworkdir=lib
if exist %frameworkdir%\%jarfile% goto JarFileOk
set frameworkdir=..\framework
:JarFileOk
set jarpath=%frameworkdir%\%jarfile%
call "%java_exe%" "-Djava.ext.dirs=%frameworkdir%" -jar %jarpath% %*
2.1 打开一张PNG图片
如下图所示,PNG图片在横向和纵向拉伸的时候都变形失真了,如下图所示:
2.2 定义不被拉伸的区间
从top边拉直线覆盖机器人,可以发现纵向机器人显示正常,如下图所示:
我们在从left边拉直线直到覆盖整个机器人,可以发现横向的机器人也显示正常,如下图所示:
三 Android系统对9Patch图片的处理
Bitmap在读取图像流数据的时候会判断图片的9Patch数据块,即NinePatchChunk,如果NinePatchChunk不为空,则该图像为NinePatchDrawable。
NinePatchDrawable会交由NinePatch处理,如下所示:
setNinePatchState(new NinePatchState(
new NinePatch(bitmap, bitmap.getNinePatchChunk(), "XML 9-patch"),
padding, dither), r);
NinePatch检验成功则调用本地方法,绘制出最终的图片,如下所示:
nativeDraw(canvas.mNativeCanvas, location,
mBitmap.ni(), mChunk, paint != null ? paint.mNativePaint : 0,
canvas.mDensity, mBitmap.mDensity);
版权声明:当我们认真的去做一件事的时候,就能发现其中的无穷乐趣,丰富多彩的技术宛如路上的风景,边走边欣赏。