2012-12-30 40 views
3

在下面的代碼中,我有兩個位圖(我省略了創建它們的代碼,因爲這與我的問題無關),並且我的佈局中也有一個ImageView。我將ImageView顯示爲第一個位圖作爲可繪製對象,然後使其顯示第二個位圖,再次將其作爲可繪製對象。Android BitmapDrawable回收/再利用

我知道位圖可以回收,我的問題與「新的BitmapDrawable」部分有關,因爲我無法確切知道BitmapDrawable是什麼。它只是一個引用,或者每次創建時都使用內存?換句話說,我爲bitmap1創建的BitmapDrawable是否需要刪除/回收,然後再爲bitmap2創建另一個BitmapDrawable?

謝謝。

Bitmap bitmap1,bitmap2; 

...assume bitmap1 and bitmap2 contain valid bitmaps... 

// get imageview 
ImageView iv = (ImageView)findViewById(R.id.my_imageview); 

// make the imageview display bitmap1 
iv.setImageDrawable(new BitmapDrawable(getResources(),bitmap1));   

// now make the imageview display bitmap2 
iv.setImageDrawable(new BitmapDrawable(getResources(),bitmap2));   
+1

只是出於好奇:爲什麼要創建'BitmapDrawable'如果你可以直接設置一個位圖到'ImageView'?參考['ImageView.setImageBitmap(Bitmap)'](http://developer.android.com/reference/android/widget/ImageView.html#setImageBitmap%28android.graphics.Bitmap%29)。如果你真的需要一個'Drawable',我會考慮使用'StateListDrawable'或'TransitionDrawable',如果你喜歡兩個圖像之間的淡入淡出效果。 –

+0

謝謝,我會試一試。 – Rick

回答

1

只要您需要,您應該保留位圖。創建新的位圖代價很高。如果有足夠的內存不可用,並且您的應用程序將在此時間停頓,則GC會觸發。

請參閱本爲有效地顯示位圖 http://developer.android.com/training/displaying-bitmaps/index.html

+4

我很清楚這一點,但它與我的問題無關。我不是在問位圖,而是在具體詢問可繪製的。它們不是同一件事。 – Rick