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

Android 改變 Bitmap 圖片顏色的實現

編輯:關於 Android 程式設計

有時候我們需要改變一張圖片的顏色,比如只替換非透明的部分。可以通過遍歷每個像素點,對符合條件的像素重新賦色,再重建 Bitmap 來實現:

public static final Bitmap createRGBImage(Bitmap bitmap, int color) {
    int bitmap_w = bitmap.getWidth();
    int bitmap_h = bitmap.getHeight();
    int[] arrayColor = new int[bitmap_w * bitmap_h];
    int count = 0;
    for (int i = 0; i < bitmap_h; i++) {
        for (int j = 0; j < bitmap_w; j++) {
            int color1 = bitmap.getPixel(j, i);
            // 這裡也可以取出 R、G、B 進行更多處理,
            // 暫時只是要處理除透明以外的顏色,改變其他顏色
            if (color1 != 0) {
                // 保留原顏色,也可在此擴展更多處理
            } else {
                color1 = color;
            }
            arrayColor[count] = color;
            count++;
        }
    }
    bitmap = Bitmap.createBitmap(arrayColor, bitmap_w, bitmap_h, Config.ARGB_4444);
    return bitmap;
}

核心思路是:通過 getPixel 讀取每個像素的顏色值,判斷是否為透明(值為 0),再按需替換為目標顏色,最後用處理後的顏色數組重建一張新的 Bitmap。如果需要更細緻的效果,還可以在循環中拆出 R、G、B 三個分量分別調整。

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