開發 Android 的時候,在許多情況下會使用到 View 的 getDrawingCache 方法來取得 View 目前顯示出來的樣子(DrawingCache),雖然算是一個還蠻方便的方法,但是這個方法卻有著許多的缺陷,它不但效能極差,內部實作方式和回傳的結果隨著 Android API 版本不同還有很大的差異。最嚴重的一點是,getDrawingCache 常常會請你吃 null。在這篇文章中,將會探討為什麼 getDrawingCache 會回傳 null,以及解決這個問題的方法。

setDrawingCacheEnabled、buildDrawingCache 和 getDrawingCache 彼此間的關係

在 Android SDK 上,所有的 View 都擁有 setDrawingCacheEnabled、buildDrawingCache 和 getDrawingCache 這三種方法,這三種看起來頗為相似的方法到底有什麼樣的情感糾葛呢?讓我們繼續看下去。

大部分的 View,如果沒有使用 setDrawingCacheEnabled 方法來啟用 View 的 DrawingCache 功能的話,那預設是不啟用的。啟用 DrawingCache 的話,使用到 getDrawingCache 方法時,會先自動去呼叫 buildDrawingCache 方法建立 DrawingCache,再將結果回傳;不啟用 DrawingCache 的話,使用 getDrawingCache 方法時,會回傳上一次使用 buildDrawingCache 方法所產生出來的結果,如果在此之前都沒有使用過 buildDrawingCache 來建立 DrawingCache 的話,那麼 getDrawingCache 就會回傳 null,當然,就算沒有啟用 DrawingCache,也還是可以事先使用 buildDrawingCache 來建立 DrawingCache,避免 getDrawingCache 傳回 null。

以下兩種方式都可以取得 View 最新的 DrawingCache:

...
view.setDrawingCacheEnabled(true);
...
Bitmap drawingCache = view.getDrawingCache();
...
...
view.buildDrawingCache();
Bitmap drawingCache = view.getDrawingCache();
...

啟用 DrawingCache 之後,就不要再呼叫 buildDrawingCache 方法了,以下寫法應該避免,會造成兩次建立 DrawingCache:

...
view.setDrawingCacheEnabled(true);
...
view.buildDrawingCache();
Bitmap drawingCache = view.getDrawingCache();
...

在使用 buildDrawingCache 方法建立 DrawingCache 的同時,Android SDK 預設會將上次的 DrawingCache 給 recycle 掉,因此不必自作聰明在使用 buildDrawingCache 方法之前,或是在 DrawingCache 啟用的狀態下使用 getDrawingCache 方法之前,把前次的 DrawingCache 給手動 recycle,如果真的這樣做的話,將會出現重複 recycle 的 RuntimeException。所以下面的寫法也應該要避免:

...
if(view.getDrawingCache() != null){
    view.getDrawingCache().recycle();;
}
view.buildDrawingCache();
Bitmap drawingCache = view.getDrawingCache();
...

為什麼 getDrawingCache 效能會很差?

文章一開始便提到 getDrawingCache 的效能極差,這是為什麼呢?就像上面提到的,一旦啟用了 DrawingCache 之後,每次呼叫 getDrawingCache,都會自動重新呼叫 buildDrawingCache 方法來建立新的 DrawingCache,但是在大部分的情況下,一個 View 的狀態是不會任意改變的,如果此時將 getDrawingCache 使用在 onDraw 之類的事件中,將會使效能非常地低落。再來就是隨著 Android API 層級愈來愈高,DrawingCache 的品質也跟著愈設愈高,在絕大部分的情況下都是使用最佔用記憶體且運算速度最慢的 ARGB_8888,過去 View 所提供的 setDrawingCacheQuality 方法已經沒有實質作用了,不管設定哪種品質,都還是會使用 ARGB_8888。

為什麼 getDrawingCache 常常傳回 null?

如果遭遇 getDrawingCache 方法傳回 null 的狀況,請先確定 View 的 DrawingCache 有無啟用,如果沒有啟用,再確定有沒有呼叫過 buildDrawingCache 方法。如果以上都確認過沒問題,再看看使用 getDrawingCache 時機是否有誤,View 一定要經過 measure 和 layout 的過程才可以被繪製出來。以下面的例子為例,即使沒有直接將 View 加入至 Activity 或是 Fragment 的 RootView 中,也可以取得 DrawingCache:

...
ViewGroup viewGroup = new FrameLayout(getContext());
ImageView image = new ImageView(getContext());
image.setImageResource(R.drawable.ic_launcher);
viewGroup.addView(image);
viewGroup.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
viewGroup.layout(0, 0, viewGroup.getMeasuredWidth(), viewGroup.getMeasuredHeight());
viewGroup.buildDrawingCache();
Bitmap bitmap = viewGroup.getDrawingCache();
...

如果很確定 View 已經有經過 measure 和 layout 且也有呼叫 buildDrawingCache(無論自動或手動)方法了,但是 getDrawingCache 卻還是傳回 null,那就是因為要繪製的 DrawingCache 太大張了,超過 Android 系統預設的 drawingCacheSize,所以系統就不給畫啦!當遇到這種狀況時,就只能放棄使用 DrawingCache 了,而事實上,這種狀況還蠻常發生的。

Android 系統預設的 DrawingCache 大小上限,在不同的裝置上有不同的設定,甚至有可能差了好幾倍,如果要查看數值的話可以在 Android SDK 中使用以下方式來取得 drawingCacheSize:

ViewConfiguration.get(context).getScaledMaximumDrawingCacheSize();

不使用 getDrawingCache 的替代方法

文章看到這裡大家應該都可以了解到 getDrawingCache 實在是異常難用,既然如此,那就完全放棄 Android 內建的 DrawingCache 機制吧!實際上,要自己實作出類似的功能並不會太難,大致上的概念是自行建立出 Bitmap,並且使用一個 Canvas 在這個 Bitmap 上作畫,只要調用 View 的 draw 方法,將自己的 Canvas 作為參數傳入,結果就會出現在 Bitmap 上了。可寫成如以下的程式:

public Bitmap getMagicDrawingCache(View view) {
    Bitmap bitmap = (Bitmap) view.getTag(cacheBitmapKey);
    Boolean dirty = (Boolean) view.getTag(cacheBitmapDirtyKey);
    int viewWidth = view.getWidth();
    int viewHeight = view.getHeight();
    if (bitmap == null || bitmap.getWidth() != viewWidth || bitmap.getHeight() != viewHeight) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
        bitmap = Bitmap.createBitmap(viewWidth, viewHeight, bitmap_quality);
        view.setTag(cacheBitmapKey, bitmap);
        dirty = true;
    }
    if (dirty == true || !quick_cache) {
        bitmap.eraseColor(color_background);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        view.setTag(cacheBitmapDirtyKey, false);
    }
    return bitmap;
}

其中,cacheBitmapKey 和 cacheBitmapDirtyKey 為相異的資源 ID(例如在專案資源中宣告的 R.id 數值),分別用來指定 View 的 Tag ID。cacheBitmapKey 的位置會存放使用這個方法建立出來的 DrawingCache;cacheBitmapDirtyKey 的位置會存放這個 View 的 DrawingCache 是否已經髒掉了(dirty)而需要呼叫 View 的 draw 方法重新繪製。DrawingCache 所用的 Bitmap 只在沒有 Bitmap 物件或是 Bitmap 物件的大小和 View 的大小不合的時候才重新建立,在建立新的 Bitmap 前會先將先前的 Bitmap 進行 recycle,新的 Bitmap 物件的參考會再被存入至 View 的 Tag 中。quick_cache 若設定為 false,則不論 DrawingCache 是否 dirty,都進行重繪,只有在 View 常常變化的時候才需要這樣做。bitmap_quality 可以設定為 Bitmap.Config.RGB_565 或是 Bitmap.Config.ARGB_8888,Bitmap.Config.ARGB_4444 已經隨著 Android API 層級愈來愈高而慢慢被禁用了,在實際應用上,RGB_565 雖然沒有透明層,但是效能會比 ARGB_8888 還要好很多。

如果要加入 View 不在 Activity 或是 Fragment 的 RootView 中的判斷的話,可以寫成以下程式:

public Bitmap getMagicDrawingCache(View view) {
    Bitmap bitmap = (Bitmap) view.getTag(cacheBitmapKey);
    Boolean dirty = (Boolean) view.getTag(cacheBitmapDirtyKey);
    if (view.getWidth() + view.getHeight() == 0) {
        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    }
    int viewWidth = view.getWidth();
    int viewHeight = view.getHeight();
    if (bitmap == null || bitmap.getWidth() != viewWidth || bitmap.getHeight() != viewHeight) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
        bitmap = Bitmap.createBitmap(viewWidth, viewHeight, bitmap_quality);
        view.setTag(cacheBitmapKey, bitmap);
        dirty = true;
    }
    if (dirty == true || !quick_cache) {
        bitmap.eraseColor(color_background);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        view.setTag(cacheBitmapDirtyKey, false);
    }
    return bitmap;
}

DrawingCache 實際應用

DrawingCache 的用途非常廣,可以用來製作 Android SDK 所沒有內建的 View,如以下時間軸樣式的 View。

用 DrawingCache 製作的時間軸樣式 View