Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 中 Bitmap 加載的記憶體優化策略

編輯:Android 開發實例

直接用 ImageView 顯示 Bitmap 會佔用大量資源,尤其是遇到大尺寸圖片時,稍不留神就可能引發內存溢出(OOM)而導致崩潰。要破解這個難題,關鍵在於對圖片進行合理的降採樣。

核心思路:inSampleSize 與 inJustDecodeBounds

BitmapFactory.Options 中的 inSampleSize 屬性能有效降低對系統資源的需求。它的含義是「縮略圖大小為原始圖片的幾分之一」——若設為 2,則取出的縮略圖寬高都是原圖的 1/2,佔用的內存便降為原圖的 1/4。

而另一個屬性 inJustDecodeBounds 則是優化計算的關鍵。SDK 文檔是這樣描述的:

If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

通俗地說,將它設為 true 後,我們可以在不解碼像素、不佔用內存的前提下,先行讀取到圖片的原始寬高(outHeight 與 outWidth),進而計算出合適的 inSampleSize 縮放值。

完整實現

布局文件 main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <ImageView
        android:id="@+id/imageview"
        android:layout_gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="center" />
</LinearLayout>

核心的 Java 代碼:

public class AndroidImage extends Activity {

    private String imageFile = "/sdcard/AndroidSharedPreferencesEditor.png";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageView myImageView = (ImageView) findViewById(R.id.imageview);

        Bitmap bitmap;
        float imagew = 300;
        float imageh = 300;

        BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
        bitmapFactoryOptions.inJustDecodeBounds = true;
        bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);

        int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight / imageh);
        int xRatio = (int) Math.ceil(bitmapFactoryOptions.outWidth / imagew);

        if (yRatio > 1 || xRatio > 1) {
            if (yRatio > xRatio) {
                bitmapFactoryOptions.inSampleSize = yRatio;
            } else {
                bitmapFactoryOptions.inSampleSize = xRatio;
            }
        } else {
            // inSampleSize = 1
        }

        bitmapFactoryOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);
        myImageView.setImageBitmap(bitmap);
    }
}

整個邏輯可謂一氣呵成:先「只讀尺寸不解碼」拿到原圖寬高,算出縮放比,再關掉 bounds 模式正式解碼。如此一來,即便原圖再大,也能被馴服在可接受的内存範圍內。

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