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

Android API 指南:Drawable 資源全解

編輯:關於 Android 開發

Android API 指南:Drawable 資源全解

繪圖資源(Drawable Resources)

可繪制資源是可以被繪制到屏幕上、並能通過 getDrawable(int) 檢索或應用於另一個 XML 資源屬性的資源,比如常見的 android:icon。Android 中的可繪制資源主要分為以下幾類:

位圖文件:位圖圖形文件(PNG、JPG、GIF),創建 BitmapDrawable。

九宮格文件:帶伸縮區域的 PNG 文件(.9.png),可根據內容縮放,創建 NinePatchDrawable。

層列表:管理一個可繪制數組,按順序繪制、索引最大者在上,創建 LayerDrawable。

狀態列表:根據不同狀態引用不同位圖的 XML(如按鈕按下時用不同圖),創建 StateListDrawable。

級別列表:管理多個備選可繪制、各分配最大級別值的 XML,創建 LevelListDrawable。

過渡繪制:在兩個繪圖資源之間淡入淡出的 XML,創建 TransitionDrawable。

插入繪制:按指定距離鑲嵌另一個可繪制的 XML,當背景 drawable 需比視圖實際范圍小時很有用。

剪輯繪制:根據當前級別裁剪另一個可繪制的 XML,創建 ClipDrawable。

縮放繪制:根據當前級別縮放另一個可繪制的 XML,創建 ScaleDrawable。

形狀繪制:限定幾何形狀(含顏色、漸變)的 XML,創建 ShapeDrawable。

此外還有如何創建 AnimationDrawable 動畫資源。

注意:顏色資源也可用於 XML 繪制。例如創建狀態列表繪制時,可引用 android:color 資源(android:drawable="@color/green")。

位圖(Bitmap)

Android 支持三種位圖格式:PNG(首選)、JPG(可接受)、GIF(不推薦)。你可以直接用文件名作為資源 ID 引用,或創建 XML 別名資源 ID。

注意:位圖文件會在構建時由 AAPT 工具自動進行無損優化,比如不需要超過 256 色的真彩 PNG 會被轉為 8 位 PNG,質量相同但更省內存。要知道,放在 drawable 目錄下的圖像二進制會在生成過程中發生改變;如果你計劃把圖像當比特流讀取,請把圖片放在 res/raw/ 文件夾,那裡的圖像不會被優化。

位圖文件

文件位置:res/drawable/filename.png(.png、.jpg 或 .gif),文件名即資源 ID。編譯後的資源數據類型為 BitmapDrawable 指針。資源引用:Java 中 R.drawable.filename,XML 中 @[package:]drawable/filename。

例:隨著保存在 res/drawable/myimage.png 的圖像,這種布局 XML 應用圖像視圖:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/myimage" />

下面的應用程序代碼把圖像作為 Drawable 對象檢索:

Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.myimage);

XML 位圖

XML 位圖是定義指向位圖文件的 XML 資源,效果相當於原始位圖文件的別名,可額外指定抖動、瓷磚等屬性。

注意:可用 <bitmap> 元素作為 <item> 的子元素。例如創建狀態列表或圖層列表時,可在 <item> 內嵌套 <bitmap> 來定義繪制項目,而無需 android:drawable 屬性。

文件位置:res/drawable/filename.xml,文件名即資源 ID。

句法:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:src="@[package:]drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" | "fill_vertical"
        | "center_horizontal" | "fill_horizontal" | "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:mipMap=["true" | "false"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

主要屬性:

android:src:繪制資源,必需。

android:antialias:布爾,啟用或禁用抗鋸齒。

android:dither:布爾,當位圖像素結構與屏幕不同(如 ARGB 8888 位圖配 RGB 565 屏幕)時,啟用或禁用抖動。

android:filter:布爾,啟用或禁用位圖篩選,縮放時讓外觀平滑。

android:gravity:關鍵詞,定義位圖比容器小時的定位方式,取值有 top、bottom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill(默認)、clip_vertical、clip_horizontal 等。

android:mipMap:布爾,啟用或禁用 mipmap 提示,默認 false。

android:tileMode:關鍵詞,定義平鋪模式,啟用後位圖重復、gravity 被忽略,取值有 disabled(默認)、clamp、repeat、mirror。

例:

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

九宮格(Nine-patch)

九補丁是一種 PNG 圖像,你可以定義當視圖內容超過正常范圍時的伸縮區域。這類圖像通常作為至少一個維度為 "wrap_content" 的視圖背景,當視圖增大以適應內容時,九宮圖像也隨之縮放以匹配視圖大小。Android 標准按鈕組件的背景就是典型例子——它必須拉伸以適應按鈕裡的文本或圖像。九宮文件既可像普通位圖那樣直接引用,也可通過 XML 定義的資源引用。

九宮格文件

文件位置:res/drawable/filename.9.png,文件名即資源 ID,資源類型為 NinePatchDrawable。

例:隨著保存在 res/drawable/myninepatch.9.png 的圖像,這種布局 XML 把九宮應用到 View:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/myninepatch" />

XML Nine-patch

指向九宮文件的 XML 資源,可指定抖動屬性。

句法:

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

其中 android:src 指向九宮文件(必需),android:dither 控制是否抖動。

層列表(LayerDrawable)

LayerDrawable 是管理其他可繪制數組的可繪制對象。列表中每個可繪按順序繪制,最後一個(列表末尾)繪制在最頂部。每個繪制由 <layer-list> 中的 <item> 表示。

句法:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:id="@[+][package:]id/resource_name"
        android:top="dimension"
        android:right="dimension"
        android:bottom="dimension"
        android:left="dimension" />
</layer-list>

<item> 屬性:android:drawable(繪制資源,必需)、android:id(唯一資源 ID,可用 findViewById 檢索修改)、android:top/right/bottom/left(像素偏移)。

所有繪制項默認縮放以適應容器大小,因此在圖層列表中擺放圖像可能增大視圖尺寸並引起縮放。若想避免縮放,可在 <item> 內嵌套 <bitmap> 並指定如 "center" 的 gravity。

例:保存於 res/drawable/layers.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:gravity="center" android:src="@drawable/android_red" />
    </item>
    <item android:top="10dp" android:left="10dp">
        <bitmap android:gravity="center" android:src="@drawable/android_green" />
    </item>
    <item android:top="20dp" android:left="20dp">
        <bitmap android:gravity="center" android:src="@drawable/android_blue" />
    </item>
</layer-list>

此例用嵌套 <bitmap> 加 "center" 定義每項繪制,確保圖像不會因偏移而被縮放。应用到 View:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/layers" />

結果是逐層偏移堆疊的圖像:

狀態列表(StateListDrawable)

StateListDrawable 用幾張不同圖片,根據對象狀態在 XML 中定義的可繪制對象。例如按鈕可在按下、獲得焦點或普通狀態下使用不同背景。它由 <selector> 中的 <item> 描述,每個 <item> 用不同屬性標明使用時機。每次狀態變化時,狀態列表從上到下遍歷並匹配當前狀態,選中的並非"最佳匹配",而是第一個滿足該狀態的最低標准項。

句法:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android"
    android:constantSize=["true" | "false"]
    android:dither=["true" | "false"]
    android:variablePadding=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

<selector> 屬性:android:constantSize(是否為常量尺寸,默認 false)、android:dither(是否抖動,默認 true)、android:variablePadding(填充是否隨狀態變化,默認 false)。

<item> 的狀態屬性含 pressed、focused、hovered、selected、checkable、checked、enabled、activated、window_focused 等,分別對應不同交互狀態。

重要:由於 Android 匹配的是列表中最先適用的項,因此若第一項包含任意狀態屬性,它就會每次都被套用——所以默認項應永遠放在最後。

例:保存於 res/drawable/button.xml:

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

应用到按鈕:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button" />

級別列表(LevelListDrawable)

管理若干備選可繪制、各分配最大級別值的繪制對象。通過 setLevel() 設置繪制的級別,加載於級別列表中級別大於或等於傳入值的繪制資源。

句法:

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/drawable_resource"
        android:maxLevel="integer"
        android:minLevel="integer" />
</level-list>

<item> 屬性:android:drawable(繪制資源,必需)、android:maxLevel(允許的最高級別)、android:minLevel(允許的最低級別)。

例:

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/status_off" android:maxLevel="0" />
    <item android:drawable="@drawable/status_on" android:maxLevel="1" />
</level-list>

应用到視圖後,可通過 setLevel() 或 setImageLevel() 改變級別。

過渡繪制(TransitionDrawable)

可在兩個可繪制資源之間淡入淡出的繪制對象。每個繪制由 <transition> 中的 <item> 表示,最多支持兩項。向下過渡調用 startTransition(),反向過渡調用 reverseTransition()。

句法:

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="https://schemas.android.com/apk/res/android">
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:id="@[+][package:]id/resource_name"
        android:top="dimension"
        android:right="dimension"
        android:bottom="dimension"
        android:left="dimension" />
</transition>

例:保存於 res/drawable/transition.xml:

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

应用到 View:

<ImageButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/transition" />

下面的代碼執行 500ms 的過渡:

ImageButton button = (ImageButton) findViewById(R.id.button);
TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
drawable.startTransition(500);

插入繪制(InsetDrawable)

按指定距離鑲嵌另一個可繪制的 XML。當視圖需要的背景比實際邊界小時非常有用。

句法:

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

屬性:android:drawable(繪制資源,必需)、android:insetTop/Right/Bottom/Left(各方向插入值,可為尺寸值或尺寸資源)。

例:

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

剪輯繪制(ClipDrawable)

根據當前級別裁剪另一個可繪制的 XML,可控制子項在寬度或高度上的裁剪比例,並用 gravity 控制裁剪位置,最常用於實現進度條。

句法:

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/drawable_resource"
    android:clipOrientation=["horizontal" | "vertical"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" | "fill_vertical"
        | "center_horizontal" | "fill_horizontal" | "center" | "fill" | "clip_vertical" | "clip_horizontal"] />

android:clipOrientation 指定裁剪方向(horizontal 或 vertical);android:gravity 指定裁剪位置。默認級別為 0(完全裁剪、不可見),級別為 10000 時圖像不裁剪、完全可見。

例:保存於 res/drawable/clip.xml:

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

下面的代碼逐步增加級別,讓圖像漸進顯示:

ImageView imageview = (ImageView) findViewById(R.id.image);
ClipDrawable drawable = (ClipDrawable) imageview.getDrawable();
drawable.setLevel(drawable.getLevel() + 1000);

這是級別為 7000 時的效果:

縮放繪制(ScaleDrawable)

根據當前級別縮放另一個可繪制的 XML。

句法:

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/drawable_resource"
    android:scaleGravity=["top" | "bottom" | "left" | "right" | "center_vertical" | "fill_vertical"
        | "center_horizontal" | "fill_horizontal" | "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:scaleHeight="percentage"
    android:scaleWidth="percentage" />

android:scaleGravity 指定縮放後的重心位置(默認 left);android:scaleHeight / android:scaleWidth 以百分比表示縮放後的相對尺寸,格式如 100%、12.5%。

例:

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/logo"
    android:scaleGravity="center_vertical|center_horizontal"
    android:scaleHeight="80%"
    android:scaleWidth="80%" />

形狀繪制(ShapeDrawable)

在 XML 中定義的通用形狀。

句法:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape=["rectangle" | "oval" | "line" | "ring"] >
    <corners
        android:radius="integer"
        android:topLeftRadius="integer"
        android:topRightRadius="integer"
        android:bottomLeftRadius="integer"
        android:bottomRightRadius="integer" />
    <gradient
        android:angle="integer"
        android:centerX="integer"
        android:centerY="integer"
        android:centerColor="integer"
        android:endColor="color"
        android:gradientRadius="integer"
        android:startColor="color"
        android:type=["linear" | "radial" | "sweep"]
        android:useLevel=["true" | "false"] />
    <padding
        android:left="integer"
        android:top="integer"
        android:right="integer"
        android:bottom="integer" />
    <size
        android:width="integer"
        android:height="integer" />
    <solid android:color="color" />
    <stroke
        android:width="integer"
        android:color="color"
        android:dashWidth="integer"
        android:dashGap="integer" />
</shape>

<shape> 的 android:shape 取值:rectangle(矩形,默認)、oval(橢圓)、line(水平線,需 <stroke> 定義線寬)、ring(環形)。ring 專屬屬性有 android:innerRadius、android:innerRadiusRatio(默認 9)、android:thickness、android:thicknessRatio(默認 3)。

<corners>:為矩形創建圓角,可用 android:radius 統一設置,或用 topLeftRadius 等分別設置各角。注意每個角初始半徑需大於 1,否則該角不會圓潤;若某角不想圓潤,可將默認 radius 設大,再對該角單獨覆蓋為 "0dp"。

<gradient>:指定漸變色。android:angle 為漸變角度(須為 45 的倍數,默認 0 從左到右,90 從下到上);android:type 有 linear(線性,默認)、radial(徑向)、sweep(掃射);另有 centerX、centerY、centerColor、startColor、endColor、gradientRadius 等。

<padding>:對包含視圖的內容(而非形狀本身)施加填充,含 left/top/right/bottom。

<size>:定義形狀尺寸(width/height)。形狀默認會縮放以適應容器,用 ImageView 時可設 scaleType 為 "center" 限制縮放。

<solid>:用純色填充形狀,android:color 為顏色值或顏色資源。

<stroke>:形狀的描邊線,含 android:width(線寬)、android:color(線色)、android:dashWidth(虛線線段大小)、android:dashGap(虛線間距)。

例:保存於 res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="45"
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF" />
    <padding
        android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

這種布局 XML 把形狀繪制應用到 View:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient_box" />

下面的應用程序代碼獲取形狀繪制並應用到一個視圖:

Resources res = getResources();
Drawable shape = res.getDrawable(R.drawable.gradient_box);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setBackground(shape);

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