Android ImageView 透明背景

針對ImageView的來源圖片為透明底色時, 需要將底色設定為透明.
否則的話,會將底下的物件覆蓋住.

將ImageView背景設定為透明的方式有以下幾種

靜態設置

在xml中設定background顏色為 #00000000

activity.xml
1
2
3
4
5
<ImageView
android:layout_width="218dp"
android:layout_height="247dp"
android:src="@drawable/test2"
android:background="#00000000"/>

亦可使用android color : transparent

activity.xml
1
2
3
4
5
<ImageView
android:layout_width="218dp"
android:layout_height="247dp"
android:src="@drawable/test2"
aandroid:background="@android:color/transparent"/>

動態設置

在程式中, 我們可以使用setBackgroundColor API 來設置

MainActivity.java
1
2
var imageView = findViewById<ImageView>(R.id.test1)
imageView.setBackgroundColor(Color.parseColor("#00000000"))

或者使用Color.TRANSPARENT

MainActivity.java
1
2
var imageView = findViewById<ImageView>(R.id.test1)
imageView.setBackgroundColor(Color.TRANSPARENT)

執行結果

作者

Nick Lin

發表於

2019-12-26

更新於

2023-01-18

許可協議


評論