萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Bitmap 核心源碼解析:創建、配置、裁剪、縮放、矩陣變換與記憶體管理

深入理解 android.graphics.Bitmap 內部實現,對優化圖片載入、避免 OOM、實現自定義圖片處理 (濾鏡、水印、拼接) 至關重要。本文基於 AOSP 原始碼 (API 30+) 解析 Bitmap 創建流程、Config 色彩模式、Native 像素存儲、createBitmap 系列重載、矩陣變換、inBitmap 重用機制與 recycle() 記憶體釋放。

類結構與關鍵欄位

public final class Bitmap implements Parcelable {
    // Native 指針,指向 SkBitmap (Skia 繪圖引擎核心結構)
    private long mNativePtr; 

    // 寬高
    private int mWidth, mHeight;

    // 色彩配置
    public enum Config {
        ALPHA_8(1),     // 僅透明通道,1 byte/像素
        RGB_565(4),     // 16位色,無透明,2 bytes/像素
        ARGB_4444(5),   // 16位色,4位透明,2 bytes/像素 (已棄用,建議用 ARGB_8888)
        ARGB_8888(6),   // 32位真彩色+透明,4 bytes/像素 (預設)
        RGBA_F16(7),    // 64位浮點 HDR (API 26+)
        HARDWARE(8);    // 純 GPU 纹理,不可直接訪問像素 (API 26+)
        final int nativeInt;
        Config(int ni) { nativeInt = ni; }
    }
    private Config mConfig;

    // 是否可變 (可被 Canvas 繪製修改)
    private boolean mMutable;

    // 生成唯一 ID (用於圖片快取 Key)
    private int mGenerationId;
}

核心靜態工廠方法解析

1. createBitmap(int width, int height, Config config)

創建可變位圖,分配 Native 像素記憶體。記憶體佔用 = width × height × bytesPerPixel (ARGB_8888 為 4 bytes)。

public static Bitmap createBitmap(int width, int height, Config config) {
    checkWidthHeight(width, height);
    long nativePtr = nativeCreate(width, height, config.nativeInt, true); // JNI 調用 Skia
    return new Bitmap(nativePtr, width, height, config, true);
}

2. createBitmap(Bitmap source, int x, int y, int width, int height)

從源 Bitmap 裁剪區域,**不複製像素數據**,共享 Native 像素緩衝區 (參考計數 +1)。修改裁剪圖會影響原圖 (除非源不可變)。

public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) {
    checkBounds(source, x, y, width, height);
    if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() && height == source.getHeight()) {
        return source; // 同條件直接返回源
    }
    long nativePtr = nativeCreateFromBitmap(source.mNativePtr, x, y, width, height);
    return new Bitmap(nativePtr, width, height, source.mConfig, source.isMutable());
}

3. createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)

**核心變換方法**:裁剪 + 矩陣變換 (縮放、旋轉、傾斜、平移) + 可選雙線性過濾。**必須分配新像素緩衝區**,不共享內存。

public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
                                  Matrix m, boolean filter) {
    checkBounds(source, x, y, width, height);
    if (m == null || m.isIdentity()) {
        return createBitmap(source, x, y, width, height); // 無變換走裁剪快速路徑
    }
    // 計算變換後邊界
    RectF srcRect = new RectF(x, y, x + width, y + height);
    RectF dstRect = new RectF();
    m.mapRect(dstRect, srcRect);
    int newWidth = Math.round(dstRect.width());
    int newHeight = Math.round(dstRect.height());

    // 創建目標 Bitmap
    Bitmap result = createBitmap(newWidth, newHeight, source.mConfig);
    Canvas canvas = new Canvas(result);
    // 調整繪製原點以對齊變換後座標
    canvas.translate(-dstRect.left, -dstRect.top);
    canvas.concat(m);
    Paint paint = new Paint();
    paint.setFilterBitmap(filter);
    if (!m.rectStaysRect()) paint.setAntiAlias(true); // 非矩形變換 (旋轉/傾斜) 開啟抗鋸齒
    canvas.drawBitmap(source, srcRect, dstRect, paint);
    return result;
}

4. createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

便利方法,內部構建縮放矩陣調用上述方法。

像素直接訪問與效能

  • getPixel(x, y) / setPixel(x, y, color):單像素操作,**極慢** (每次 JNI 邊界調用),僅供調試/極少量修改。
  • getPixels(int[] pixels, offset, stride, x, y, width, height):批量複製像素到 Java 陣列,**單次 JNI 複製整塊區域**,效能高數百倍。
  • copyPixelsFromBuffer(Buffer) / copyPixelsToBuffer(Buffer):直接操作 ByteBuffer (Direct Buffer),零拷貝與 JNI 交互,最高效,適合 OpenGL 紋理上傳、圖片編解碼器對接。

inBitmap 記憶體重用機制 (API 19+ / KitKat)

解碼新圖片時,若指定 BitmapFactory.Options.inBitmap 指向一個**可變、相同尺寸/配置、未被使用**的舊 Bitmap,解碼器將直接重用其 Native 像素緩衝區,**避免重複分配/GC**,大幅降低列表滾動、圖片切換時的記憶體抖動。

// LruCache 存放可重用 Bitmap
LruCache reusableBitmaps = new LruCache<>(20);

public void decodeWithReuse(String path, ImageView imageView) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inMutable = true; // 必須可變
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    
    // 從快取尋找符合尺寸/配置的 Bitmap
    Bitmap reusable = findReusableBitmap(options.outWidth, options.outHeight, options.inPreferredConfig);
    if (reusable != null) {
        options.inBitmap = reusable;
        reusableBitmaps.remove(reusable.getGenerationId()); // 從快取移除,標記為使用中
    }

    Bitmap bitmap = BitmapFactory.decodeFile(path, options);
    if (bitmap != null) {
        imageView.setImageBitmap(bitmap);
        // 圖片不再顯示時 (如 RecyclerView 回收),歸還快取
        imageView.setTag(bitmap); // 附帶引用
    }
}

private Bitmap findReusableBitmap(int w, int h, Config config) {
    for (Bitmap b : reusableBitmaps.snapshot()) {
        if (b.getWidth() == w && b.getHeight() == h && b.getConfig() == config && !b.isRecycled()) {
            return b;
        }
    }
    return null;
}

記憶體釋放:recycle() vs 依賴 GC

  • recycle() (API 1-10 必須):** 立即釋放 Native 像素緩衝區,Java 對象變為「死」狀態,再次使用會拋出异常。已棄用 (API 31+),現代 Android 依賴 GC 自動回收 (Bitmap 實現 Finalizer),但手動調用仍可在特定場景 (大量臨時 Bitmap、記憶體緊張) 提前釋放。
  • inBitmap 重用 是現代高效管理核心,Glide/Fresco/Coil 內部均大量使用。

硬體位圖

Config.HARDWARE (API 26+) 將像素數據完全存放於 GPU 顯存,**不可直接讀寫像素** (getPixels 會拋異常),但繪製效能極高、不佔用 Java 堆/本地堆。Bitmap.createBitmap(width, height, Config.HARDWARE) 或解碼時 options.inPreferredConfig = Config.HARDWARE。適用於大型靜態圖片、相簿縮圖、SurfaceView 直接渲染。

總結:Bitmap 選型指南

場景推薦 Config關鍵參數
一般 UI 圖片、網路圖片、相簿ARGB_8888inSampleSize 縮放、inBitmap 重用
大量小圖標、記憶體極度受限RGB_565無透明通道,省 50% 記憶體
Alpha 遮罩、字體輪廓、單通道ALPHA_8極省記憶體
HDR 內容、高動態範圍渲染RGBA_F16API 26+,需硬體支援
大型靜態圖、相簿網格、Video 幀HARDWAREAPI 26+,不可讀像素,極高繪製效能
Bitmap 是 Android 圖形系統的核心貨幣。掌握其創建、變換、記憶體管理機制,是從「會用 API」進階到「高效能圖形開發」的必經之路。
copyright © 萬盛學電腦網 all rights reserved