在 Android 開發中,經常需要把 View 轉換成 Bitmap。常見場景包括:對整個螢幕視圖截圖並生成圖片;在 Coverflow 中把一頁頁的 View 轉為 Bitmap 以實現陰影、倒影等複雜圖形效果;還有一些動態即時的 View,為了方便觀察與記錄資料,需要臨時生成靜態的 Bitmap。
方法一,直接建立 Bitmap 並繪製:
public static Bitmap convertViewToBitmap(View view, int bitmapWidth, int bitmapHeight){
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
view.draw(new Canvas(bitmap));
return bitmap;
}
方法二,透過 DrawingCache:
public static Bitmap convertViewToBitmap(View view){
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
一般情況下這兩種方法都能正常工作,但有時會出現問題(例如 Bitmap 全黑或為 null)。主要原因在於 DrawingCache 的大小超過了系統允許的上限。我們來看 buildDrawingCache() 中的一段判斷:
if (width <= 0 || height <= 0 ||
(width * height * (opaque && !translucentWindow ? 2 : 4) > ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
destroyDrawingCache();
return;
}
其中 width * height * (...) 計算的是當前所需的 cache 大小,而 getScaledMaximumDrawingCacheSize() 取得的是系統提供的最大 DrawingCache 值。當所需大小超過系統上限時,生成的 Bitmap 就會出問題,此時取得的 Bitmap 為 null。
關鍵在於先用 measure 與 layout 觸發 View 的正確測量,再取得 DrawingCache:
public static Bitmap convertViewToBitmap(View view){
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
透過 getMeasuredWidth() 與 getMeasuredHeight() 取得實際的長寬,此時 Bitmap 便能正確取得,避免了因尺寸不當造成的空指針問題。