首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android ImageView 背景透明化:圖片格式與程式碼雙重保障

     編輯:程式設計疑難解答

核心原則:透明度由圖片本身決定

ImageView 顯示的圖片背景是否透明,取決於圖片資源本身是否包含 Alpha 通道。

最佳實踐

  1. 使用 PNG 格式:支援 Alpha 通道,設計階段即在圖片編輯軟體(如 Photoshop)將背景設為透明並匯出 PNG。
  2. XML 佈局直接引用:
    <ImageView
        android:src="@drawable/transparent_icon"
        android:background="@android:color/transparent" />
    

動態載入時的處理

若必須在執行期對 Bitmap 處理透明色(例如指定某顏色變透明):

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.source_img);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); // 確保可修改

int targetColor = Color.RED; // 要變透明的顏色
int transparent = Color.TRANSPARENT;

int width = bitmap.getWidth();
int height = bitmap.getHeight();
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        if (bitmap.getPixel(x, y) == targetColor) {
            bitmap.setPixel(x, y, transparent);
        }
    }
}
imageView.setImageBitmap(bitmap);

注意:雙重迴圈處理像素效能較差,大圖建議使用 OpenGL ES 或 RenderScript 加速。

常見誤區:setAlpha(0)

imageView.setAlpha(0) 會將整個 ImageView(含前景圖片)設為完全透明,等同於 setVisibility(View.INVISIBLE),並非僅移除背景。

總結

優先使用預處理透明 PNG;動態需求時操作 Bitmap 像素;切勿誤用 setAlpha 控制背景透明度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved