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

Android Drawable 詳解:從 BitmapDrawable 到 ClipDrawable

編輯:關於 Android 程式設計

Drawable 是 Android 中非常常見的資源類型。它可以是一張圖片,也可以是通過 XML 定義的形狀、漸變、層疊或裁剪效果。掌握 Drawable,可以讓界面背景與圖形效果更加靈活。

BitmapDrawable

BitmapDrawable 是最常見的 Drawable 之一,通常顯示一張位圖。除了代碼創建之外,也可以通過 XML 定義。

<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:antialias="true"
    android:src="@drawable/p2"
    android:dither="true"
    android:filter="true"
    android:gravity="top|left"
    android:tileMode="repeat" />

其中,tileMode 常用取值包括 disable、repeat、mirror 與 clamp。repeat 會重複鋪滿,clamp 會延伸邊緣顏色,mirror 則會以鏡像方式鋪展。

當圖片小於 View 時,使用 repeat 可以看到圖片重複顯示。

如果改為 clamp,邊緣顏色會自動延伸。

如果改為 mirror,圖片會以倒影形式重複。

ShapeDrawable

ShapeDrawable 常用於绘制純色、漸變、圓角或邊框背景。相比直接使用圖片,XML shape 更輕量,也更容易修改。

LayerDrawable

LayerDrawable 可以將多個 Drawable 按層疊加。常用於實現帶邊框的輸入框或複合背景。

<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/lineColor" />
        </shape>
    </item>
    <item android:bottom="8dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/lineColor2" />
        </shape>
    </item>
</layer-list>

LevelListDrawable

LevelListDrawable 可以根據 level 值切換不同 Drawable,常用於播放進度、電量或等級展示。

<level-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/p2" android:maxLevel="10" android:minLevel="0" />
    <item android:drawable="@drawable/p1" android:minLevel="11" android:maxLevel="20" />
</level-list>

通過 setImageLevel() 可以動態切換圖片。

TransitionDrawable

TransitionDrawable 可以實現兩個 Drawable 之間的淡入淡出效果。

<transition xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/p1" />
    <item android:drawable="@drawable/p2" />
</transition>

調用 startTransition() 即可觸發過渡動畫。

InsetDrawable 與 ClipDrawable

InsetDrawable 可以將一個 Drawable 嵌入到內部,並設置四周間距。ClipDrawable 則可以根據 level 對 Drawable 進行裁剪,常用於進度條效果。

<clip xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/p1"
    android:clipOrientation="horizontal"
    android:gravity="left" />

level 取值通常為 0 到 10000,0 表示完全裁剪,10000 表示完全不裁剪。

總的來說,Drawable 體系非常豐富。理解 BitmapDrawable、ShapeDrawable、LayerDrawable、LevelListDrawable、TransitionDrawable 等常見類型,可以幫助我們更靈活地實現界面效果。

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