Button button1 = (Button) findViewById(R.id.bt);
InputStream stream = null;
try {
stream = getAssets().open("button_compiled.9.png");
} catch (IOException e1)
{
e1.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(stream);
byte[] chunk = bitmap.getNinePatchChunk();
boolean bResult = NinePatch.isNinePatchChunk(chunk);
NinePatchDrawable patchy = new NinePatchDrawable(bitmap, chunk,new Rect(), null);
button1.setBackgroundDrawable(patchy);
:
assets中使用的.9.png圖片必須要編譯過,否則無法正常使用,如:中的第二個按鈕,已經失真。
編譯.9.png
.9.png可以使用draw9patch.bat工具來製作,這樣的png用圖片瀏覽工具開啟可以看到圖片的周圍有黑色的像素點,這是就是使用draw9patch.bat工具畫上去的。當經過android編譯後,從apk包中解壓出來.9.png,這時使用圖片瀏覽工具開啟可以看到圖片的周圍有黑色的像素點消失了。這就是編譯過的.9.png。
編譯.9.png: 調用系統的aapt.ext工具對包含png的程式進行處理,zip包,解壓zip得到的.9.png即編譯過的.9.png
建一個java工程並將android.jar和AndroidManifest.xml放到工程目錄下,建一個圖片目錄res/drawable
工程如:
使用aapt命令:
aapt p -M E:\workspace\CompileNinePatch\AndroidManifest.xml -S E:\workspace\CompileNinePatch\res -I E:\workspace\CompileNinePatch\android.jar -F C:\Users\liuyt\Desktop\temp.zip
將編譯後的zip包產生到案頭
解壓後可以看到編譯好的.9.png