Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 大圖與多圖載入優化:從根上遠離 OOM

編輯:關於 Android 程式設計

相機照片的解析度通常遠高於手機螢幕,若直接將原始圖片塞進 ImageView,容易讓應用程式占用過多記憶體,甚至引發 OutOfMemoryError。載入圖片前,先判斷實際顯示尺寸,再決定是否縮放,是避免 OOM 的第一步。

先讀取邊界,不配置像素記憶體

BitmapFactory 的各個 decode 方法都支援 Options 參數。將 inJustDecodeBounds 設為 true,可以在不真正建立 Bitmap 的情況下取得寬高與 MIME 類型。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;

用 inSampleSize 降低解析度

取得原圖尺寸後,可依目標檢視大小計算 inSampleSize。若 ImageView 只需顯示縮圖,就沒有必要載入完整大圖。

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / reqHeight);
        final int widthRatio = Math.round((float) width / reqWidth);
        inSampleSize = Math.min(heightRatio, widthRatio);
    }
    return inSampleSize;
}

多圖清單要搭配記憶體快取

在 ListView、GridView 或 ViewPager 中,使用者滑動會不斷載入圖片。此時可將已載入的 Bitmap 放入 LruCache,讓最近使用的圖片保留在記憶體中,減少重複解碼。

int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSize = maxMemory / 8;
LruCache memoryCache = new LruCache(cacheSize) {
    protected int sizeOf(String key, Bitmap bitmap) {
        return bitmap.getByteCount() / 1024;
    }
};

搭配背景執行緒載入與快取命中判斷,才能在大量圖片場景下兼顧流暢度與穩定性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved