2014-02-10 69 views
1

我有一個可修改爲9的補丁作爲XML。當我嘗試使用BitmapFactory.decode來獲取位圖時,它會返回null。無論如何,從這個資源獲取位圖嗎?Android將Ninepatch資源轉換爲位圖

nine_patch.xml:

<?xml version="1.0" encoding="utf-8"?> 
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android" 
    android:src="@drawable/empty_icon_video" > 

</nine-patch> 

而且代碼:

BitmapFactory.decodeResource(mResources, resId); 

回答

6
Bitmap bmp = Bitmap.createBitmap(yourWidth, yourHeight, Bitmap.Config.ARGB_8888); 
Drawable drawable = getResources().getDrawable(R.drawable.resId); 
Canvas canvas = new Canvas(bmp); 
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
drawable.draw(canvas); 

試試這個。現在位圖將會在其上繪製九塊圖。您可以提供不同的寬度和高度。

+0

我的問題是,我從BitmapDrawable繼承,所以超級構造函數將位圖不ninepatchdraawable – youssefhassan

+0

見編輯答案 – Triode

1

這裏需要使用NinePatchDrawable API -

NinePatchDrawable npDrawable = (NinePatchDrawable)getResources().getDrawable(R.drawable.empty_icon_video);