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

Android 圖片載入與記憶體溢出防護實作

編輯:關於 Android 程式設計

在 Android 中載入大量圖片時,最令人頭痛的就是記憶體溢出(OOM)問題。本文整理了一套完整的做法,從圖片資源的組織、螢幕尺寸計算,到異步載入與縮放,一步步教你如何安全地把圖片顯示到 GridView 上。

一、準備圖片資源

先以陣列的形式管理要顯示的圖片資源 ID,並建立一個集合用來保存載入後的 Bitmap:

private int fore[];
private int back[];
fore = new int[]{R.drawable.a0, R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4,
    R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
    R.drawable.a910, R.drawable.a911, R.drawable.a912, R.drawable.a913, R.drawable.a914};
back = new int[]{R.drawable.b0, R.drawable.b1, R.drawable.b2, R.drawable.b3, R.drawable.b4,
    R.drawable.b5, R.drawable.b6, R.drawable.b7, R.drawable.b8, R.drawable.b9,
    R.drawable.b910, R.drawable.b911, R.drawable.b912, R.drawable.b913, R.drawable.b914};

// 用來保存載入的圖片
private List<Bitmap> bitmapResource = new ArrayList<Bitmap>();

GridView grid;      // 類似九宮格的圖片顯示控制項
Handler handler;    // 用來傳遞訊息的 Handler

二、計算顯示寬度並異步載入

取得螢幕寬度後,透過 AsyncTask 在背景執行緒中完成耗時的圖片縮放,避免阻塞 UI 主執行緒:

int width = (int) (getWindowManager().getDefaultDisplay().getWidth() / density);// 取得螢幕寬度
ImageResource ir = new ImageResource();

// 使用 getPicture() 方法載入圖片
public void getPicture() {
    new AsyncTask<Object, Object, Object>() {
        @Override
        protected Object doInBackground(Object... params) {
            // 背景執行,耗時操作都放在這裡
            publishProgress();               // 更新任務進度
            loadingBitmap(getResources(), width, 3);// 縮放圖片,3 為顯示列數
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            // doInBackground 完成後,此方法會在 UI 執行緒被呼叫
            handler.removeCallbacks(update);
            message.setVisibility(View.GONE);
            author_message.setVisibility(View.GONE);
            grid.setVisibility(View.VISIBLE);
            grid.setNumColumns(3);           // 設定列數
            grid.setHorizontalSpacing(20);   // 欄間距
            grid.setVerticalSpacing(40);     // 列間距
            grid.setAdapter(adapter);
            grid.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                    Intent intent = new Intent();
                    intent.setClass(MenuActivity.this, ShowActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("num", position);   // 傳遞位置值
                    intent.putExtras(bundle);
                    MenuActivity.this.startActivity(intent);
                }
            });
            adapter.notifyDataSetChanged();  // 通知 UI 依新資料重繪
            super.onPostExecute(result);
        }

        protected void onProgressUpdate(Object... values) {
            handler = new Handler();
            handler.post(update);            // 依執行緒更新進度
            super.onProgressUpdate(values);
        }
    }.execute();
}

三、關鍵:圖片縮放避免 OOM

真正防止記憶體溢出的核心,在於 BitmapFactory.Options 的 inJustDecodeBounds 與 inSampleSize 兩個屬性:

public void loadingBitmap(Resources resources, int width, int num) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    // 僅回傳圖片的寬高,不實際載入,因此幾乎不佔記憶體,能大幅降低 OOM 發生率
    opts.inJustDecodeBounds = true;  // 設為 true 時不返回實際 bitmap,只取得解碼邊界資訊
    Bitmap temp = BitmapFactory.decodeResource(resources, fore[0], opts);

    // 向上取整計算縮放比例
    int radio = (int) Math.ceil(opts.outWidth / (width * 1.0 / num - 30));
    // Math.ceil(12.2) → 13;Math.ceil(12.7) → 13;Math.ceil(12.0) → 12
    opts.inSampleSize = radio;       // 縮略圖為原圖的幾分之一
    if (null != temp) {
        temp.recycle();              // 回收
    }
    opts.inJustDecodeBounds = false; // 設為 false 才能依縮放比例載入想要的圖片

    for (int i = 0; i < fore.length; i++) {
        Bitmap bitmap = BitmapFactory.decodeResource(resources, fore[i], opts);
        bitmapResource.add(bitmap);  // 逐一加入集合
    }
}

四、使用 BaseAdapter 綁定資料

BaseAdapter adapter = new BaseAdapter() {
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView iv = new ImageView(MenuActivity.this);
        iv.setMaxWidth(width / 3 - 30);       // 設定寬度
        iv.setAdjustViewBounds(true);         // 保持寬高比
        iv.setImageBitmap(ir.getIconBitmap(position));
        return iv;
    }
    @Override public long getItemId(int position) { return position; }
    @Override public Object getItem(int arg0) { return arg0; }
    @Override public int getCount() { return ir.size(); }
};

最後,透過 Handler 搭配 postDelayed 實作一個輕量的進度更新機制,當進度達到 100% 時停止輪詢:

Runnable update = new Runnable() {
    @Override
    public void run() {
        int progress = ir.getProgress();
        if (null != message) {
            message.setText("數據加載中(" + progress + "%),請稍等……\n\n");
        }
        if (100 == progress) {
            handler.removeCallbacks(update); // 載入完成,停止定時器
        } else {
            handler.postDelayed(update, 200); // 每 0.2 秒更新一次
        }
    }
};
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved