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

Android Drawable 全解(二):BitmapDrawable、Inset、Clip、Rotate 與 AnimationDrawable

編輯:關於 Android 程式設計

本節引言:上一節已經介紹了四個 Drawable——ColorDrawable、NinePatchDrawable、ShapeDrawable 與 GradientDrawable。這一節接著看另外五個:BitmapDrawable、InsetDrawable、ClipDrawable、RotateDrawable、AnimationDrawable。

大綱圖

1. BitmapDrawable

對 Bitmap 的一種封裝,可以設定它包裝的 bitmap 在 BitmapDrawable 區域中的繪製方式:平鋪填充、拉伸填滿,或保持圖片原始大小。以 <bitmap> 為根節點。

相關屬性:

  • src:圖片資源
  • antialias:是否啟用抗鋸齒
  • filter:是否啟用 bitmap 過濾,開啟後縮放顯示會比較平滑
  • dither:是否對 bitmap 做抖動處理,低品質螢幕上漸層會比較自然
  • gravity:若 bitmap 比容器小,可設定它在容器中的相對位置
  • tileMode:平鋪填充模式。設定這個屬性後 gravity 會被忽略,可選值有:
    • disabled:整個圖案拉伸填滿
    • clamp:保持原圖大小
    • repeat:平鋪
    • mirror:鏡像平鋪

分別的效果如下:

① XML 定義 BitmapDrawable:

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

② 等效的 Java 程式碼:

BitmapDrawable bitDrawable = new BitmapDrawable(bitmap);
bitDrawable.setDither(true);
bitDrawable.setTileModeXY(TileMode.MIRROR, TileMode.MIRROR);

2. InsetDrawable

表示把一個 Drawable 嵌入到另一個 Drawable 裡面,並在內部留一些間距,概念上類似 Drawable 的 padding 屬性。但要注意兩者的差別:padding 表示的是 Drawable 的內容與 Drawable 本身的邊距,而 InsetDrawable 表示的是 兩個 Drawable 與容器之間的邊距。

當控制項需要的背景比實際的邊框小時,比較適合使用 InsetDrawable。比如它可以解決自定義 Dialog 與螢幕之間的間距問題——相信做過的朋友都知道,即使設定了 layout_margin 也沒有用,這個時候就可以派上用場:只需為 InsetDrawable 設定 insetXxx 指定不同方向的邊距,然後設為 Dialog 的背景即可。

相關屬性:

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

① XML 中使用:

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

② Java 程式碼中使用:

InsetDrawable insetDrawable = new InsetDrawable(
        getResources().getDrawable(R.drawable.test1), 10, 10, 10, 10);

執行結果:

3. ClipDrawable

Clip 可以譯為「剪」。我們可以把 ClipDrawable 理解為從 bitmap 上剪下一個部分。Android 中的進度條就是用 ClipDrawable 實作的,它依設定的 level 值決定剪切區域的大小。根節點是 <clip>。

相關屬性:

  • clipOrientation:剪切方向,可設水平或垂直
  • gravity:從哪個位置開始裁剪
  • :引用的 drawable 資源,為空時需要一個 Drawable 類型的子節點,寫法是在 <clip> 裡放 <bitmap android:src="@drawable/test4" android:gravity="center" />

使用示例:核心就是透過程式碼修改 ClipDrawable 的 level。這裡實作一個類似進度條的效果,注意 level 的值是 0~10000。

① 定義 ClipDrawable 資源檔:

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

② 在主版面配置中放一個 ImageView,把 src 指向 clipDrawable:

注意是 src,如果寫成 background 會拿到空參照而報錯。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.jay.example.drawabletest.MainActivity">

    <ImageView
        android:id="@+id/imgShow1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/clip_one" />
</LinearLayout>

③ MainActivity 透過 setLevel 控制截取區域:

package com.jay.example.drawabletest;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.drawable.ClipDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView imgShow1;
    private ClipDrawable cd;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                cd.setLevel(cd.getLevel() + 500);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgShow1 = (ImageView) findViewById(R.id.imgShow1);
        // 核心:取得 ImageView 的 Drawable 並轉型
        cd = (ClipDrawable) imgShow1.getDrawable();

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0x123);
                if (cd.getLevel() >= 10000) {
                    timer.cancel();
                }
            }
        }, 0, 300);
    }
}

執行效果:

4. RotateDrawable

用來旋轉 Drawable,同樣透過 setLevel() 控制,最大值也是 10000。

相關屬性:

  • fromDegrees:起始角度,對應最低的 level 值,預設 0
  • toDegrees:結束角度,對應最高的 level 值,預設 360
  • pivotX:參照點的 x 座標,取值 0~1,預設 50%(即 0.5)
  • pivotY:參照點的 y 座標,取值 0~1,預設 50%
  • drawable:設定位圖資源
  • visible:設定 drawable 是否可見

如果出现旋轉後圖片顯示不完整的情況,可以調整 pivotX / pivotY 解決。

角度示意:

使用示例:在第三點的 clipDrawable 上稍作修改即可。

① 定義 rotateDrawable 資源檔:

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

② activity_main.xml 中把 src 指向上述 drawable,MainActivity 只需把 ClipDrawable 改成 RotateDrawable:

package com.jay.example.drawabletest;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.drawable.RotateDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private ImageView imgShow1;
    private RotateDrawable cd;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                if (cd.getLevel() >= 10000) {
                    Toast.makeText(MainActivity.this, "轉完了~", Toast.LENGTH_LONG).show();
                }
                cd.setLevel(cd.getLevel() + 300);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgShow1 = (ImageView) findViewById(R.id.imgShow1);
        cd = (RotateDrawable) imgShow1.getDrawable();

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0x123);
                if (cd.getLevel() >= 10000) {
                    timer.cancel();
                }
            }
        }, 0, 300);
    }
}

執行結果:

5. AnimationDrawable

最後一個是用來實作 Android 幀動畫的:把一系列 Drawable 依指定順序一幀一幀播放。Android 的動畫體系很豐富,有補間動畫的平移、縮放、旋轉、透明度等,本節只介紹 AnimationDrawable 這個幀動畫方案,其餘留待動畫章節再談。根節點是 <animation-list>。

相關屬性:

  • oneshot:是否只播放一次;false 代表循環播放
  • duration:幀間隔時間,通常設為 300 毫秒左右

取得 AnimationDrawable 實例後,需要呼叫它的 start() 方法才會播放。這裡有個經典的坑:如果在 onCreate() 中直接呼叫 start(),是不會有任何效果的,因為 View 尚未完成初始化。解法是用 Handler 延遲播放,例如 handler.postDelayed()。

程式碼示例:

① 定義 AnimationDrawable 的 XML 資源檔:

<?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/anim1" android:duration="300" />
    <item android:drawable="@drawable/anim2" android:duration="300" />
    <item android:drawable="@drawable/anim3" android:duration="300" />
    <item android:drawable="@drawable/anim4" android:duration="300" />
    <item android:drawable="@drawable/anim5" android:duration="300" />
</animation-list>

② activity_main.xml 設定 src,然後在 MainActivity 中:

package com.jay.example.drawabletest;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView imgShow1;
    private AnimationDrawable ad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgShow1 = (ImageView) findViewById(R.id.imgShow1);
        // 核心:取得 AnimationDrawable 並延遲啟動
        ad = (AnimationDrawable) imgShow1.getDrawable();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ad.start();
            }
        }, 300);
    }
}

執行結果:

幾點補充

  • ClipDrawable 與 RotateDrawable 的 level 是 0~10000,這個非直觀的範圍是官方定義的常數,寫動畫時要記得換算。
  • AnimationDrawable 很吃記憶體:幀動畫會把所有幀的 Bitmap 一次載入記憶體,幀數多、圖片大時極易 OOM。實務上通常改用 AnimationDrawable 搭配壓縮過的 WebP,或直接改用屬性動畫/Lottie。
  • 記得在生命週期裡 stop():離開畫面時若未停止幀動畫,它會持續佔用資源。
  • deprecated 提醒:getResources().getDrawable(int) 在 API 22 之後已標記為 deprecated,新專案請改用 ContextCompat.getDrawable(context, id) 或 Resources.getDrawable(id, theme)。

用得好,這些 Drawable 可以省下大量自定義 View 的程式碼;用得不好,它們會變成難以追查的記憶體問題來源。理解每個 Drawable 對應的場景,比記住所有屬性更重要。

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