您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

把 View 轉成 Bitmap:兩種做法與黑圖陷阱

編輯:iOS 相關資訊

一、為什麼需要把 View 轉成 Bitmap

Android 開發中經常需要把 View 轉成 Bitmap。常見場景包括:對整個畫面截圖存成圖片;在 Coverflow 這類效果中把每一頁 view 轉成點陣圖,以便實作陰影、倒影等複雜的視覺處理;還有一些即時更新的動態 View,為了方便觀察或記錄數據,需要臨時產生一張靜態影像。

二、第一種做法

這是我常用的寫法,直接建立一張 Bitmap 再讓 view 畫上去:

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;
}

或者走 drawing cache 的路子:

public static Bitmap convertViewToBitmap(View view) {
    view.buildDrawingCache();
    Bitmap bitmap = view.getDrawingCache();
    return bitmap;
}

多數情況下這兩個方法都能正常工作。但有時會出問題——生出來的 Bitmap 全黑,或者根本拿到 null。根因在於所需的 cache 大小超過了系統允許的上限。看看 buildDrawingCache() 裡的這段判斷:

if (width <= 0 || height <= 0 ||
    (width * height * (opaque && !translucentWindow ? 2 : 4)
     > ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
    destroyDrawingCache();
    return;
}

其中 width 與 height 是該 view 繪製時的寬高,因此 width * height * (opaque && !translucentWindow ? 2 : 4) 算的就是當前所需的 cache 大小;而 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize() 是系統提供的上限。當所需 cache 超過上限時,generateDrawingCache 會直接 destroyDrawingCache() 並返回,此時 getDrawingCache() 拿到的自然就是 null。

三、比較可靠的做法

關鍵在於先讓 view 完成一次測量與配置,用它實際量到的尺寸去計算,就能避開這個問題:

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 就能正確產生了。

補充一點:如果你的 view 尺寸本來就大於系統 cache 上限,那麼 buildDrawingCache 這條路仍然會失敗。這種情況下建議改回第一種寫法,用 createBitmap 搭配 Canvas 直接繪製,並視需要設定 bitmap 的取樣與色彩配置。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved