[英]Create drawable from bitmap
您可以使用
Drawable d = new BitmapDrawable(getResources(), my_bmp);
包裹位圖的Drawable,可以平鋪,拉伸或對齊。 您可以從文件路徑,輸入流,通過XML膨脹或從Bitmap對象創建BitmapDrawable。
BitmapDrawable(Resources res, Bitmap bitmap)
從位圖創建可繪制對象,並根據資源的顯示指標設置初始目標密度。
還要看一下@公共構造函數
http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html
試試這個加載Bitmap
作為Bitmap Drawable
創建ImgDrawableFromFile(Resources res, String file_name)
如下所示
Drawable d = null;
public Drawable ImgDrawableFromFile(Resources res, String file_name) {
myBitmap = null;
File imgFile = new File(
"/data/data/yourpkgname/app_my_sub_dir/images/" + file_name);
if (imgFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
if (myBitmap != null) {
d = new BitmapDrawable(res, myBitmap);
return d;
} else {
return null;
}
}
return null;
}
現在稱為這個函數
img.setBackgroundDrawable(ImgDrawableFromFile(getResources(), "1.jpg")); // pass your saved file name as second argument
派對晚了一點,但我顯然有誤會。 提供的答案確實是正確的:
Drawable d = new BitmapDrawable(getResources(),bitmap);
在這種情況下, getResources()
是Context
或Activity
可用的方法,僅用於找出屏幕密度並相應地調整Drawable。
因此,即使從雲中加載圖像,Igor仍然可以調用getResources()。
快樂編碼
BitmapDrawable(Bitmap bitmap)
構造函數已被deprecated
您可以使用
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
您可以使用BitmapDrawable類從位圖獲取Drawable
位圖可繪制參考
如果毛羅·班茲(Mauro Banze)參加晚會很晚,那么我真的不知道我在做什么。 但是對於那些在這里拼命尋找解決方案的人,這是我所做的:
當將Project從JavaFX引入Android時,我偶然發現了同樣的問題。 我想重用我的大多數“數據”類,這些類僅管理和提供我的數據,而對UI沒有影響。
講足夠的故事,我們開始:
問題:
Drawable
才能在屏幕上顯示位圖。 Drawable
Context
或非Activity
類中執行此操作,因為我們需要Resources
。 因此,為什么不將它保存為Bitmap
直到我們需要繪制它(這肯定會在Context
或Activity
類中發生)。
我創建了一個名為BitmapImage
的類。 看起來像這樣:
public class BitmapImage {
private final Bitmap bitmap;
public BitmapImage (Bitmap bitmap) {
this.bitmap = bitmap;
}
public Bitmap getBitmap() {
return bitmap;
}
public Drawable getDrawable(Resources res) {
return new BitmapDrawable(res,getBitmap());
}
這個非常簡單的類“保存”位圖。 因此,與其使用Drawable
,不如使用BitmapImage
直到真正需要Drawable
為止。
那時,您應該在Activity
或Context
並且可以在其中調用Drawable foo = anyBitmapImage.getDrawable(getResource())
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.