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

Android Drawable 與 LayerDrawable 完全解析

編輯:關於 Android 程式設計

先看一個實際需求:做出一個外圈白色描邊、內圈綠色填色、中央再疊一張圖示的圓形按鈕。

用 layer-list 就能乾淨地解決:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="oval">
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="3dp"
                android:color="@android:color/white" />
            <size
                android:height="55dp"
                android:width="55dp" />
            <padding
                android:bottom="15dp"
                android:left="15dp"
                android:right="15dp"
                android:top="15dp" />
        </shape>
    </item>

    <item>
        <shape android:shape="oval">
            <solid android:color="@android:color/holo_green_light" />
            <stroke
                android:width="3dp"
                android:color="@android:color/white" />
            <size
                android:height="40dp"
                android:width="40dp" />
            <padding
                android:bottom="15dp"
                android:left="15dp"
                android:right="15dp"
                android:top="15dp" />
        </shape>
    </item>

    <item>
        <scale
            android:drawable="@drawable/repair_iconaa"
            android:scaleWidth="50%"
            android:scaleHeight="50%" />
    </item>

</layer-list>

從 Drawable 基礎重新梳理

Android 把「可繪製的物件」抽象成 Drawable,不同的圖形與圖像資源各自對應不同的實作類別。Framework 已提供多種具體實作,日常開發幾乎不會直接 new 這些類別——把資源丟進 res/drawable,剩下交給 SDK 就好, XML 中用 @drawable 引用,程式碼中用 id 引用。

一個容易忽略的細節:Drawable 預設是記憶體共享的。同一個 Drawable 在不同地方被使用時,指向的是同一份資源、共享同一份狀態;一旦在其中一處修改,所有使用點都會跟著改變。若需要獨立狀態,記得呼叫 mutate()。

Android 內建的 Drawable 類型包括:ColorDrawable、GradientDrawable、BitmapDrawable、NinePatchDrawable、InsetDrawable、ClipDrawable、ScaleDrawable、RotateDrawable、AnimationDrawable、LayerDrawable、LevelListDrawable、StateListDrawable、TransitionDrawable。以下逐一說明。

Shape 基本語法

shape 是 GradientDrawable 在 XML 中的根節點,位置放在 res/drawable/xxx.xml,程式碼中以 R.drawable.xxx 引用,版面中以 android:background="@drawable/xxx" 引用。

<shape android:shape="rectangle|oval|line|ring">

常用子節點與屬性:

  • <gradient> 漸層:startColor 起始色、endColor 結束色、centerColor 中間色;angle 為漸層角度(0 由上而下、90 由左至右,須為 45 的整數倍);type 可為 linear(線性)、radial(環形)、sweep(扇形掃描)。
  • <solid> 填色:android:color 指定單色。若同時設定了 solid,會覆蓋 gradient 的效果。
  • <stroke> 描邊:width 寬度、color 顏色、dashWidth 虛線段長、dashGap 虛線間距。
  • <corners> 圓角:radius 統一圓角半徑,或分別指定 topLeftRadius、topRightRadius、bottomLeftRadius、bottomRightRadius。
  • <padding> 內距:left / top / right / bottom。

一、ColorDrawable

最簡單的 Drawable,代表單色可繪製區域。以 color 作為根節點,只有一個 android:color 屬性,且 Framework 未提供修改該顏色的 API,設定後便無法直接更改。

<?xml version="1.0" encoding="utf-8"?>
<color xmlns:android="https://schemas.android.com/apk/res/android"
    android:color="#FF0000" />

用 Java 建立:

ColorDrawable drawable = new ColorDrawable(0xffff0000);

要注意 Android 用一個 int 表示顏色,四個位元組分別是 Alpha、Red、Green、Blue,各佔 8 個 bit,範圍 0~255。在 XML 中可以省略 Alpha(#ff0000 就是紅色),但在程式碼中若省略 Alpha 會變成完全透明:0xFFFF0000 是紅色,而 0xFF0000 雖然數值上看起來像紅,實際上 alpha 為 0,畫不出任何東西。這是初學者最常踩的坑之一。

二、GradientDrawable

表示一個漸層區域,可實現線性漸層、發散漸層與平鋪漸層,能做出相當華麗的介面效果。相較於 ColorDrawable,它的結構複雜得多:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <size />      <!-- 定義區域大小 -->
    <gradient />  <!-- 設定漸層效果 -->
    <solid />     <!-- 設定背景色,會覆蓋 gradient -->
    <stroke />    <!-- 設定邊框 -->
    <padding />   <!-- 設定內距 -->
</shape>

三種典型漸層寫法:

<?xml version="1.0" encoding="utf-8"?>
<!-- 線性漸層效果的橢圓 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="oval">
    <gradient
        android:startColor="#ff0000"
        android:centerColor="#00ff00"
        android:endColor="#0000ff"
        android:angle="90" />
    <stroke
        android:width="3dip"
        android:color="#fff"
        android:dashWidth="4dip"
        android:dashGap="5dip" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<!-- 平鋪漸層效果的圓環 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:innerRadiusRatio="8"
    android:thicknessRatio="3"
    android:useLevel="false">
    <gradient
        android:type="sweep"
        android:useLevel="false"
        android:startColor="#ff0000"
        android:endColor="#0000ff"
        android:centerColor="#00ff00" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<!-- 發散漸層效果的圓 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:innerRadius="0dip"
    android:thickness="70dip"
    android:useLevel="false">
    <gradient
        android:type="radial"
        android:useLevel="false"
        android:gradientRadius="70"
        android:startColor="#ff0000"
        android:endColor="#0000ff"
        android:centerColor="#00ff00" />
</shape>

三者執行結果如下:


圖 6-1 線性漸層效果的橢圓


圖 6-2 平鋪漸層效果的圓環


圖 6-3 發散漸層效果的圓

三、BitmapDrawable

對 bitmap 的一層包裝,可指定它在區域內的繪製方式——平鋪填滿、拉伸填滿或保持原始尺寸,也能用 gravity 決定對齊方式。

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:src="@drawable/png_icon_416"
    android:tileMode="mirror"
    android:antialias="true"
    android:dither="true" />

tileMode="mirror" 會讓小圖在水平與垂直方向做鏡面平鋪,接縫處比 repeat 自然許多。等價的 Java 寫法:

Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.png_icon_416);
BitmapDrawable mBitmapDrawable = new BitmapDrawable(mBitmap);
mBitmapDrawable.setTileModeXY(TileMode.MIRROR, TileMode.MIRROR);
mBitmapDrawable.setAntiAlias(true);
mBitmapDrawable.setDither(true);
mDrawable = mBitmapDrawable;


圖 6-4 BitmapDrawable 執行結果

四、NinePatchDrawable(點九圖)

點九圖是 Android 特有的圖片格式,副檔名為 .9.png。由於裝置解析度五花八門,一般切圖被拉伸後邊角容易模糊失真;點九圖技術可以讓圖片在水平與垂直方向同時拉伸,在多解析度下仍保持完美顯示,漸層質感與圓角精細度都不會流失。

顧名思義,它把一張 PNG 切成九個部分(九宮格):四個角不拉伸、四條邊分別只做單一方向的拉伸、中央區域自由拉伸。四角固定,所以圓角永遠清晰;邊框固定,所以不會被拉粗。

四条黑線的含義如下:左側與上方黑線圍成的矩形是拉伸區域;下側與右側黑線圍成的矩形是內容顯示區域。黑線可以連續也可以不連續,但為求最佳效果,建議使用連續線段。


圖 6-5 點九圖示意

導入點九圖之後,只需一套切圖即可適配各種解析度,同時大幅縮小安裝包。Framework 在渲染時採用高效演算法,App 無須額外處理就能自適應拉伸,程式碼量與開發工時都省下不少。

<?xml version="1.0" encoding="utf-8"?>
<nine-patch xmlns:android="https://schemas.android.com/apk/res/android"
    android:src="@drawable/droid_logo"
    android:dither="true" />

也可以用 bitmap 包裝,Framework 會依 android:src 指向的圖片型別自動判斷:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:src="@drawable/droid_logo"
    android:dither="true" />


圖 6-6 原始點九圖


圖 6-7 點九圖拉伸後的效果

兩點提醒:其一,雖然 Java 也能建立 NinePatchDrawable,實務上極少這麼做——因為 SDK 會在編譯時把點九圖處理成特殊格式,程式碼只能吃已編譯的資源,未編譯的一律被當成 BitmapDrawable。其二,點九圖只適用於拉伸,不適用於壓縮;若需適配大量解析度,應把點九圖做得小一點,留出拉伸餘裕。

五、InsetDrawable

把一個 Drawable 嵌入另一個 Drawable 內部,並在四周留出間距。它與 padding 的差別在於:padding 是「Drawable 內容與自身邊緣」的距離,inset 是「Drawable 與外部容器」的距離。當需要的背景比實際邊框小時,用 inset 最合適。

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/bitmap_bell"
    android:insetLeft="20dp"
    android:insetRight="20dp"
    android:insetTop="20dp"
    android:insetBottom="20dp" />


圖 6-8 InsetDrawable 執行結果

六、ClipDrawable

對一個 Drawable 做剪切,可控制剪切區域與對齊方式。Android 的進度條正是用它實作的,依 level 決定剪切範圍。

level 的規則:0 時完全不可見,10000 時完全顯示,透過 setLevel(int) 設定。

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="https://schemas.android.com/apk/res/android"
    android:clipOrientation="horizontal"
    android:drawable="@drawable/bitmap_android"
    android:gravity="left">
</clip>

若沒有 android:drawable,就必須提供任意型別的 Drawable 作為子節點:

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="https://schemas.android.com/apk/res/android"
    android:clipOrientation="horizontal"
    android:gravity="left">
    <bitmap
        android:src="@drawable/android_text"
        android:gravity="center" />
</clip>

七、ScaleDrawable

對 Drawable 做縮放,依 level 控制縮放比例,並可指定在容器中的對齊方式。

<?xml version="1.0" encoding="utf-8"?>
<!-- android:scaleGravity 可設定縮放後的對齊方式 -->
<scale xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/smiley_smile"
    android:scaleWidth="100%"
    android:scaleHeight="100%">
</scale>


圖 6-10 ScaleDrawable 執行結果

八、RotateDrawable

對 Drawable 做旋轉,依 level 控制角度,並可指定旋轉中心。

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/smiley_smile"
    android:pivotX="50%"
    android:pivotY="50%">
</rotate>


圖 6-11 RotateDrawable 執行結果

九、AnimationDrawable(影格動畫)

把一系列 Drawable 依序逐格播放,可用 android:oneshot 決定是否循環。

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/level1" android:duration="300" />
    <item android:drawable="@drawable/level2" android:duration="300" />
    <item android:drawable="@drawable/level3" android:duration="300" />
    <item android:drawable="@drawable/level4" android:duration="300" />
    <item android:drawable="@drawable/level5" android:duration="300" />
</animation-list>

定義好之後必須主動呼叫 start() 才會播放。這裡有個經典陷阱:在 Activity 的 onCreate() 中直接呼叫 start() 不會有任何效果,因為 View 尚未完成初始化。正確做法是用 Handler 延遲觸發:

mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        ((AnimationDrawable) mDrawable).start();
    }
}, 1000);

十、LayerDrawable

管理一組 Drawable,每個佔據不同圖層,繪製時依序全部畫到畫布上。各層之間即使重疊也互不干擾——這正是本文開頭那個圓形按鈕的實作原理。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/layer1" />
    <item android:drawable="@drawable/layer2" />
    <item android:drawable="@drawable/layer3" />
</layer-list>


圖 6-12 LayerDrawable 執行結果

十一、LevelListDrawable

管理一組 Drawable,每個對應一段 level 區間;繪製時依 level 值挑出對應的那一個。順序上要注意,maxLevel 必須由小到大排列。

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:maxLevel="2000"  android:drawable="@drawable/level1" />
    <item android:maxLevel="4000"  android:drawable="@drawable/level2" />
    <item android:maxLevel="6000"  android:drawable="@drawable/level3" />
    <item android:maxLevel="8000"  android:drawable="@drawable/level4" />
    <item android:maxLevel="10000" android:drawable="@drawable/level5" />
</level-list>


圖 6-13 LevelListDrawable 執行結果(一)


圖 6-14 LevelListDrawable 執行結果(二)

十二、StateListDrawable

管理一組 Drawable,每個對應一組狀態組合。比對邏輯近似 Java 的 switch-case:由上而下逐一比對,一旦命中就回傳對應 Drawable。因此必須把最精確的條件放在最前面,由精確到粗略排序,否則會永遠命中第一條而失效。

這個類型在 Android 中無處不在——基本上所有按鈕的背景都靠它切換外觀,因為按鈕有按下、選取、預設、停用等多種狀態。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item
        android:state_focused="false"
        android:state_pressed="false"
        android:drawable="@drawable/gradient_normal" />

    <item
        android:state_pressed="true"
        android:drawable="@drawable/gradient_pressed" />

    <item
        android:state_focused="true"
        android:drawable="@drawable/gradient_focused" />
</selector>


圖 6-15 預設狀態


圖 6-16 Focused 狀態


圖 6-17 Pressed 狀態

十三、TransitionDrawable

LayerDrawable 的子類別,只管理兩層 Drawable,並提供透明度過渡動畫,能做出交叉淡入淡出的切換效果。

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/smiley_smile" />
    <item android:drawable="@drawable/smiley_smile_glasses" />
</transition>

使用時需主動呼叫 startTransition() 啟動正向切換,或 reverseTransition() 反向切換,兩者都接受一個毫秒數作為動畫時長。同樣地,由於 View 尚未完成初始化,這類動畫也建議用 Handler 延遲觸發:

mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        ((TransitionDrawable) mDrawable).startTransition(2000);
    }
}, 1000);

選用建議

這十三種型別並不需要死背,掌握幾條判斷線即可:單色用 ColorDrawable、漸層與圓角用 GradientDrawable(即 shape)、圖片拉伸用 NinePatchDrawable、按鈕外觀切換用 StateListDrawable、多層疊圖用 LayerDrawable、進度類用 ClipDrawable 或 LevelListDrawable、圖示切換動畫用 TransitionDrawable。真正需要自訂 Drawable 子類別的場合並不多,多數需求用 XML 宣告就能解決,而且可讀性遠高於程式碼。

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