Android 透過 Shape Drawable 的 <gradient> 標籤即可在 XML 定義線性、放射、掃射漸層,無需圖片資源即可實現豐富視覺效果。本文示範最常用的線性漸層範例與屬性對照。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:startColor="#4a557c"
android:endColor="#62c4e7" />
</shape>
<View
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/gradient_bg" />
| 屬性 | 說明 | 典型值 |
|---|---|---|
| android:type | 漸層類型 | linear (預設) / radial / sweep |
| android:angle | 線性漸層角度(須為 45 的倍數) | 0, 90, 180, 270 |
| android:startColor | 起始顏色 | #RRGGBB 或 #AARRGGBB |
| android:endColor | 結束顏色 | 同上 |
| android:centerColor | 中間顏色(可選) | 同上 |
| android:centerX / centerY | 放射漸層中心點 (0~1) | 0.5 |
| android:gradientRadius | 放射漸層半徑(需 type=radial) | 100dp |
| android:useLevel | 是否作為 LevelListDrawable | false |
<gradient
android:type="linear"
android:angle="0"
android:startColor="#FF0000"
android:centerColor="#00FF00"
android:endColor="#0000FF" />
<corners> 圓角、<stroke> 邊框、<padding> 內距,構建完整元件外觀。GradientDrawable 呼叫 setColors()、setOrientation() 實現動畫漸層。純 XML 即可實現高效能漸層背景,減少 APK 體積並支援任意解析度縮放。