標籤:
郭孝星
微博:郭孝星的新浪微博
郵箱:[email protected]
部落格: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 offrem Copyright (C) 2008 The Android Open Source Projectremrem 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 atremrem http://www.apache.org/licenses/LICENSE-2.0remrem Unless required by applicable law or agreed to in writing, softwarerem 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 andrem limitations under the License.rem don‘t modify the caller‘s environmentsetlocalrem 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=%~f0rem Change current directory and drive to where the script is, to avoidrem issues with directories containing whitespaces.cd /d %~dp0rem Check we have a valid Java.exe in the path.set java_exe=call lib\find_java.batif not defined java_exe goto :EOFset jarfile=draw9patch.jarset frameworkdir=.set libdir=if exist %frameworkdir%\%jarfile% goto JarFileOk set frameworkdir=libif exist %frameworkdir%\%jarfile% goto JarFileOk set frameworkdir=..\framework:JarFileOkset 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);
著作權聲明:當我們認真的去做一件事的時候,就能發現其中的無窮樂趣,豐富多彩的技術宛如路上的風景,邊走邊欣賞。
【Android應用開發技術:使用者介面】9Patch圖片設計