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

Android Drawable 全景圖鑑:從 XML 節點到實現類

編輯:關於 Android 程式設計

為什麼要系統地認識 Drawable

日常開發中,我們絕大多數時候並不直接 new 出某個 Drawable 實現類,而是寫 XML。只有當需要在運行時動態修改 Drawable 的屬性時,才會真正用到那些具體類型提供的 API。

理解 Drawable 的一個關鍵前提是:XML 中的根節點與 Drawable 的實現類是一一對應的。記住這層映射關係,寫配置文件時心裡就有底了。

Android 在 android.graphics.drawable 包中提供了大量實現類:ColorDrawable、GradientDrawable、BitmapDrawable、NinePatchDrawable、InsetDrawable、ClipDrawable、ScaleDrawable、RotateDrawable、AnimationDrawable、LayerDrawable、LevelListDrawable、StateListDrawable、TransitionDrawable 等等。

XML 標籤與實現類對照表

XML 標籤實現類說明
—AnimatedRotateDrawable可對另一個 Drawable 做旋轉動畫
animation-listAnimationDrawable由一串 Drawable 組成的逐幀動畫,可作為 View 背景
bitmapBitmapDrawable包裝一張位圖,支援平鋪、拉伸與對齊
clipClipDrawable依據 level 裁剪另一個 Drawable,常用於進度條
colorColorDrawable用單一顏色填充畫布
insetInsetDrawable把另一個 Drawable 按指定距離內縮
layer-listLayerDrawable管理一組按順序疊放的 Drawable
level-listLevelListDrawable管理多個帶 level 區間的備選 Drawable
nine-patchNinePatchDrawable可拉伸的 .9 圖,能指定拉伸區域
rotateRotateDrawable依據 level 旋轉另一個 Drawable
scaleScaleDrawable依據 level 縮放另一個 Drawable
selectorStateListDrawable依據狀態切換顯示不同圖片
shapeGradientDrawable畫形狀的基本方式,支援漸變、圓角、描邊等
transitionTransitionDrawablelayer-list 的擴展,可在兩層之間做交叉淡入淡出

ColorDrawable:一塊純色

ColorDrawable 代表單色可繪製區域。它包裝了一種固定顏色,被繪製到畫布時會用該顏色填充 Paint,畫出一塊純色區域。

XML 方式

<TextView
    android:id="@+id/id_tv_colorDrawableDemo_Xml"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/colordrawable_xml"
    android:text="ColorDrawable-ByXml"
    android:textColor="@color/bg_black"
    android:textSize="20sp" />

顏色本身定義在 color.xml 中,使用時直接引用即可:

<color xmlns:android="https://schemas.android.com/apk/res/android"
    android:color="@color/skyblue" />

代碼方式

用代碼寫的時候有個容易踩的坑:必須把 Alpha 通道寫全。Android 用一個 int 表示顏色,四個字節分別是 Alpha、R、G、B,各佔 8 位,取值 0~255。XML 裡可以省略 Alpha(例如 #ff0000 就是紅色),但代碼裡省略了就等於完全透明,畫上去什麼也看不見。

public class ColorDrawableActivity extends AppCompatActivity {
  private TextView mIdTvColorDrawableDemo;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_color_drawable);
    mIdTvColorDrawableDemo = findViewById(R.id.id_tv_colorDrawableDemo_javaCode);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
      // 0xffff0000:Alpha=ff,紅色
      mIdTvColorDrawableDemo.setBackground(new ColorDrawable(0xffff0000));
    }
  }
}

順帶一提,setBackground 是 API 16 之後才加入的。

GradientDrawable:形狀與漸變的主力

GradientDrawable 表示一個漸變區域,可以實現線性漸變、發散漸變與平鋪(sweep)漸變。XML 中以 <shape> 作為根節點,可搭配多個子節點與屬性使用。

核心子節點 <gradient>

常用屬性整理如下:

  • startColor / centerColor / endColor:起始色、中間色、結束色。
  • type:漸變類型,可取 linear、radial、sweep。
  • centerX / centerY:中間色座標,取值 0~1。
  • angle:僅 linear 有效,必須是 45 的倍數。
  • gradientRadius:僅 radial、sweep 有效,radial 必須設置。
  • useLevel:是否按 level 繪製漸變。

線性漸變 linear

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="oval">
  <gradient
      android:angle="90"
      android:centerColor="#00ff00"
      android:endColor="#0000ff"
      android:startColor="#ff0000" />
  <stroke
      android:width="3dip"
      android:color="#fff"
      android:dashGap="5dip"
      android:dashWidth="4dip" />
</shape>

發散漸變 radial

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thickness="100dp"
    android:useLevel="false">
  <gradient
      android:centerColor="#FFEB82"
      android:endColor="#35B2DE"
      android:gradientRadius="50"
      android:startColor="#DEACAB"
      android:type="radial"
      android:useLevel="false" />
</shape>

平鋪漸變 sweep

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:innerRadiusRatio="8"
    android:shape="ring"
    android:thicknessRatio="3"
    android:useLevel="false">
  <gradient
      android:centerColor="#FFEB82"
      android:endColor="#35B2DE"
      android:startColor="#DEACAB"
      android:type="sweep"
      android:useLevel="false" />
</shape>

在佈局中引用

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
  <TextView
      android:id="@+id/id_tv_gradientDrawableDemo_Xml1"
      android:layout_width="200dp"
      android:layout_height="200dp"
      android:layout_gravity="center_horizontal"
      android:layout_margin="10dp"
      android:background="@drawable/gradient_linear"
      android:gravity="center"
      android:text="線性漸變 linear-ByXml"
      android:textColor="@color/bg_black"
      android:textSize="20sp" />
  <TextView
      android:id="@+id/id_tv_gradientDrawableDemo_Xml2"
      android:background="@drawable/gradient_radial"
      android:text="發散漸變 radial-ByXml" />
  <TextView
      android:id="@+id/id_tv_gradientDrawableDemo_Xml3"
      android:background="@drawable/gradient_sweep"
      android:text="平鋪漸變 sweep-ByXml" />
</LinearLayout>

BitmapDrawable:位圖的容器

BitmapDrawable 是對 bitmap 的一種包裝,可以設置它在自身區域內的繪製方式:平鋪填滿、拉伸填滿,或保持原始大小;也可以透過 gravity 指定對齊方式。XML 中以 <bitmap> 作為根節點。

常用屬性:

  • src:圖片資源。
  • antialias:是否開啟抗鋸齒。
  • filter:是否開啟位圖過濾,開啟後縮放顯示更平滑。
  • dither:是否對位圖做抖動處理。
  • gravity:當位圖比容器小時,指定它在容器中的位置。
  • tileMode:平鋪模式,設置後 gravity 會被忽略。可選 disabled(整體拉伸)、clamp(保持原圖大小)、repeat(平鋪)、mirror(鏡像平鋪)。

XML 方式

<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:dither="true"
    android:src="@drawable/ic_launcher"
    android:tileMode="mirror" />

代碼方式

public class BitmapDrawableActivity extends AppCompatActivity {
  private ImageView mIdBitmapDrawableXml;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bitmap_drawable);
    mIdBitmapDrawableXml = findViewById(R.id.id_bitmapDrawable_xml);

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
      mIdBitmapDrawableXml.setBackground(mBitmapDrawable);
    } else {
      AlertUtil.showDialogWithClose(this, "API<16 不支援 setBackground 屬性設置");
    }
  }
}

這種寫法囉嗦又少用,了解即可。

InsetDrawable:給 Drawable 加一層內縮邊距

InsetDrawable 把一個 Drawable 嵌入到另一個 Drawable 內部,並留出間距。它和 padding 有本質區別:padding 描述的是 Drawable 內容與自身邊界的距離,而 InsetDrawable 描述的是兩個 Drawable 與容器之間的邊距。當控件需要的背景比實際邊界更小的時候,它就派上用場。

一個典型場景是自訂 Dialog 與屏幕之間的間距問題——你可能發現設置 layout_margin 完全沒有效果,這時給 Dialog 換上一個 InsetDrawable 背景,透過 insetLeft / insetRight / insetTop / insetBottom 指定各方向邊距即可解決。

相關屬性:

  • drawable:引用的 Drawable,若為空則必須提供一個 Drawable 類型的子節點。
  • visible:設置是否可見。
  • insetLeft / insetRight / insetTop / insetBottom:四個方向的邊距。

剩下的 ClipDrawable、ScaleDrawable、RotateDrawable、LayerDrawable、StateListDrawable 等,思路都類似:本身不畫內容,而是修飾或組織其他 Drawable。掌握 level、gravity、layer 順序這幾個關鍵概念,基本就能應付絕大多數業務需求。

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