2012-09-29 104 views
6

我試圖從我的設備sd卡載入一個png圖像作爲drawable。 我用下面的功能,但它不工作:從sd卡載入drawable

public Drawable getDrawable() 
{ 
return new BitmapDrawable(imagePath); 
} 

的映像路徑是:MNT/SD卡/ MyFolder中/ image.png

應用崩潰時,我試圖調用該方法時,應該如何我加載位於我的SD卡中的png圖像並將其轉換爲Drawable對象?

+1

看看'decodeFile' http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeFile(java.lang.String) – Doomsknight

+0

@Doomsknight你能舉個例子嗎?我正在尋找BitmapFromFile,但找不到任何有關它的信息。 – idish

+0

@Doomsknight我明白了,所以我必須將位圖轉換爲可繪製的對象? – idish

回答

13

直接從文件路徑實際上有一個BitmapDrawable構造函數。您正在使用的方法已被刪除。嘗試:

Drawable myDrawable = new BitmapDrawable(getResources(), pathName); 

如果不工作,嘗試讓一個位圖,並創建從中可抽拉:

位圖可以decodeFile

創建您可以使用它像這樣:

Bitmap myBitmap = BitmapFactory.decodeFile(pathName); 

然後,您可以使用位圖進行繪圖等。

位圖轉換爲可繪製使用

Drawable myDrawable = new BitmapDrawable(getResources(), myBitmap); 

以獲取更多信息看Here (Bitmaps)Here (Bitmap Drawables)

+0

第一段代碼應該是= new BitmapDrawable(),因爲它是一個構造函數。 –

+0

@JohnJSmith改變了。 :) – Doomsknight

0

我簡單的做這樣的

public Drawable getDrawableFromPath(String filePath) { 
    Bitmap bitmap = BitmapFactory.decodeFile(filePath); 
    //Here you can make logic for decode bitmap for ignore oom error. 
    return new BitmapDrawable(bitmap); 
}