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

Android 圖像處理入門:Bitmap 與 BitmapDrawable 的關係與實作

編輯:關於 Android 程式設計

在 Android 裡處理圖片,Bitmap 與 BitmapDrawable 這對搭檔幾乎無可迴避。理解兩者的分工,是寫好任何圖像相關功能的第一步。本文從最單純的載入方式出發,一路寫到自訂圖片輪播。

三種載入圖片的方式

直接用最簡單的圖片資源

使用 Drawable 物件

使用 Bitmap 與 BitmapDrawable 物件

關鍵觀念釐清

三者並非平行選項,而是層層包覆的關係。Bitmap 是記憶體中的一塊像素矩陣,本身不具備「能被 View 繪製」的能力;BitmapDrawable 則是把它包裝成 Drawable,讓 ImageView 之類的元件可以接受。當你寫 setImageResource 時,系統在幕後做的其實就是同一件事——把資源解碼成 Bitmap,再包成 BitmapDrawable 交給 View。

正因為 Bitmap 背後是一整塊連續的像素記憶體,它的生命週期管理才格外重要。一張 1080p 的 ARGB_8888 圖片,光是像素資料就要吃掉約 8MB,動輒數張同存便足以觸發 OOM。因此替換圖片前主動 recycle 舊的 Bitmap,是一個值得養成的習慣。

實作:從 assets 輪播圖片

public class MainActivity extends Activity {

    String[] images;
    ImageView image;
    int currentImg;
    AssetManager asset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.imageBit);

        try {
            asset = getAssets();
            images = asset.list("");
        } catch (Exception e) {
            e.printStackTrace();
        }

        findViewById(R.id.btnBit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentImg >= images.length) {
                    currentImg = 0;
                }

                // 跳過非圖片檔案
                while (!images[currentImg].endsWith(".png")
                        && !images[currentImg].endsWith(".jpg")
                        && !images[currentImg].endsWith(".gif")) {
                    currentImg++;
                    if (currentImg >= images.length) {
                        currentImg = 0;
                    }
                }

                InputStream assetFile = null;
                try {
                    assetFile = asset.open(images[currentImg++]);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 換圖之前先回收上一張,避免記憶體堆積
                BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
                if (drawable != null && !drawable.getBitmap().isRecycled()) {
                    drawable.getBitmap().recycle();
                }

                image.setImageBitmap(BitmapFactory.decodeStream(assetFile));
            }
        });
    }
}

幾點實務提醒

asset.list("") 傳入空字串代表列出 assets 根目錄,這裡用它來取得圖檔清單,因此實作時要留意根目錄若混有 .html、.txt 等其他檔案,務必像範例那樣做副檔名過濾。另外 decodeStream 回傳的 Bitmap 若為 null(例如檔案損毀),後續 recycle 邏輯雖然不會崩潰,畫面卻會停在舊圖上,正式專案裡建議加上 null 判斷與提示。

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