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

Android API Guides 導讀:屬性動畫(Property Animation)

編輯:關於 Android 程式設計

屬性動畫系統是 Android 3.0 起提供的一套管線,威力在於它能對任何物件的屬性做動畫,不管該屬性會不會被畫到螢幕上。傳統的 View 動畫只能改動繪製結果,屬性動畫則是直接改寫物件上的欄位值,讓目標在指定時間內從起始值過渡到結束值。

你可以控制哪些細節

  • Duration(持續時間):動畫長度,預設 300ms。
  • Time Interpolation(時間插值):屬性值如何隨時間變化,決定是等速還是加減速。
  • Repeat Count and Behavior(重複次數與行為):要不要重播、重播幾次,以及是否來回反向播放。
  • Animator Sets(動畫集):多個動畫可以並行、序列播放,或加上延遲。
  • Frame Refresh Delay(幫幀更新延遲):預設每 10ms 更新一次,實際速度取決於系統當時有多忙。

它是怎麼算出中間值的

先看一個最簡單的例子:某個假想物件要動畫它的 x 座標(也就是螢幕上的水平位置),duration 設為 40ms,移動距離 40px。每 10ms 刷新一次,也就是每幀水平推進 10px;40ms 結束時停在 x=40。這是線性插值,等速移動。

圖 1:線性動畫

若改成非線性插值,同樣是 40ms 走 40px,但開頭加速、結尾減速。整段距離一樣,起訣與終點附近走的距離明顯小於中段。

圖 2:非線性動畫

這套計算由三個角色協作完成:

圖 3:動畫的計算流程

ValueAnimator 負責計時:它知道動畫已經跑了多久,也能算出當前屬性值。TimeInterpolator 定義插值方式,TypeEvaluator 定義如何依型別計算屬性值。以圖 2 為例,插值器是 AccelerateDecelerateInterpolator,評估器是 IntEvaluator。

計算過程分兩步。首先 ValueAnimator 依「已過時間 / 總時長」算出經過分數(0 到 1),0 代表 0%、1 代表 100%;圖 1 中 t=10ms 時是 0.25。接著把這個分數交給 TimeInterpolator 轉成插值分數;圖 2 因為開頭慢,t=10ms 的插值分數約 0.15,小於 0.25。最後由 TypeEvaluator 依插值分數算出該幀的實際屬性值,並呼叫 ValueAnimator.AnimatorUpdateListener 把值套用到目標物件上。

ValueAnimator

最直觀的用法:

ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);
animation.setDuration(1000);
animation.start();

這段程式會在 1000ms 內計算 0 到 1 之間的值。若要動畫自訂型別,則搭配自訂的 TypeEvaluator:

ValueAnimator animation = ValueAnimator.ofObject(new MyTypeEvaluator(),
        startPropertyValue, endPropertyValue);
animation.setDuration(1000);
animation.start();

但要注意:ValueAnimator 本身不會改動任何物件。它只是把值算出來,剩下的套用動作要你自己在 AnimatorUpdateListener 裡透過 getAnimatedValue() 完成。

ObjectAnimator:懶人版

ObjectAnimator 是 ValueAnimator 的子類別,把計時引擎與「直接更新目標屬性」的能力結合起來,因此不必再自己寫 AnimatorUpdateListener:

ObjectAnimator anim = ObjectAnimator.ofFloat(foo, "alpha", 0f, 1f);
anim.setDuration(1000);
anim.start();

要讓它正常運作,有幾個前提:

  1. 目標屬性必須有對應的 setter,命名為 setPropertyName()(駝峰式)。屬性名是 foo,就得有 setFoo()。若沒有,你可以幫目標類別補上、寫一個包裝類別轉發,或者退回使用 ValueAnimator。
  2. 工廠方法只給一個值時,該值被視為結束值,因此還需要 getter 來取得起始值,命名為 getPropertyName()。
  3. setter 與起始值的型別必須一致,例如 targetObject.setPropName(float) 與 getPropName() 回傳 float。
  4. 若動畫的屬性不會自動觸發重繪(例如自訂的顏色屬性),你可能需要在 onAnimationUpdate 回呼裡呼叫 invalidate()。反之,View 內建的 setter 如 setAlpha()、setTranslationX() 已經處理好失效重繪,不必多此一舉。

AnimatorSet:編排多個動畫

很多時候動畫之間有先後依賴。AnimatorSet 可以把它們綁在一起,指定並行、序列或延遲:

AnimatorSet bouncer = new AnimatorSet();
bouncer.play(bounceAnim).before(squashAnim1);
bouncer.play(squashAnim1).with(squashAnim2);
bouncer.play(squashAnim1).with(stretchAnim1);
bouncer.play(squashAnim1).with(stretchAnim2);
bouncer.play(bounceBackAnim).after(stretchAnim2);

ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(bouncer).before(fadeAnim);
animatorSet.start();

更完整的示範可參考 API Demos 裡的 Bouncing Balls。

監聽動畫事件

Animator.AnimatorListener:

  • onAnimationStart():動畫啟動。
  • onAnimationEnd():動畫結束。被取消的動畫也會觸發。
  • onAnimationRepeat():動畫重播。
  • onAnimationCancel():動畫被取消。

ValueAnimator.AnimatorUpdateListener:

  • onAnimationUpdate():每一幀都會呼叫,用 getAnimatedValue() 取出當前值。使用 ValueAnimator 時這個監聽器是必需的。

若只想實作其中一兩個方法,繼承 AnimatorListenerAdapter 會比直接實作介面輕鬆:

ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);
fadeAnim.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        balls.remove(((ObjectAnimator) animation).getTarget());
    }
});

為 ViewGroup 的版面變化加動畫

LayoutTransition 可以為容器內子 View 的出現與消失加上動畫,共四種事件:

  • APPEARING:子 View 出現時運行。
  • CHANGE_APPEARING:因新成員加入,既有子 View 位置改變時運行。
  • DISAPPEARING:子 View 消失時運行。
  • CHANGE_DISAPPEARING:因子 View 移除,其餘子 View 位置改變時運行。

透過 setAnimator() 傳入自訂的 Animator 即可替換外觀;什麼都不設就使用系統預設。

最省力的做法是直接在 XML 上打開開關:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id="@+id/verticalContainer"
    android:animateLayoutChanges="true" />

設為 true 之後,容器內子 View 的新增、刪除以及剩餘 View 的位移都會自動帶上版面轉場動畫。

TypeEvaluator:動畫一個系統不認識的型別

系統內建的評估器有 IntEvaluator、FloatEvaluator 與 ArgbEvaluator。型別不在其中時,自己實作 TypeEvaluator 介面即可,唯一要寫的是 evaluate():

public class FloatEvaluator implements TypeEvaluator<Object> {
    public Object evaluate(float fraction, Object startValue, Object endValue) {
        float startFloat = ((Number) startValue).floatValue();
        float endFloat = ((Number) endValue).floatValue();
        return startFloat + fraction * (endFloat - startFloat);
    }
}

特別注意:傳進 evaluate() 的 fraction 已經是插值後的分數,所以你不必在評估器裡再考慮插值器的存在。

TimeInterpolator:控制節奏

插值器決定「時間 → 進度」的映射。系統在 android.view.animation 中提供了 AccelerateDecelerateInterpolator、AccelerateInterpolator、AnticipateInterpolator、OvershootInterpolator、BounceInterpolator、CycleInterpolator、DecelerateInterpolator、LinearInterpolator 等常用實作,不夠用就實作 TimeInterpolator。

以預設的兩個為例:

// AccelerateDecelerateInterpolator
public float getInterpolation(float input) {
    return (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}

// LinearInterpolator
public float getInterpolation(float input) {
    return input;
}

以 1000ms 的動畫比較兩者:

已過時間經過分數 / 線性插值分數加減速插值分數
000
2000.20.1
4000.40.345
6000.60.8
8000.80.9
100011

線性版本每 200ms 穩定推進 0.2;加減速版本在 200–600ms 之間走得比線性快,頭尾則明顯放慢。

Keyframe:指定關鍵時刻的狀態

Keyframe 是「時間 / 值」對,讓你能在動畫的特定時刻定義特定狀態,每個 keyframe 還能帶自己的插值器:

Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
Keyframe kf1 = Keyframe.ofFloat(.5f, 360f);
Keyframe kf2 = Keyframe.ofFloat(1f, 0f);

PropertyValuesHolder pvhRotation =
        PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
ObjectAnimator rotationAnim =
        ObjectAnimator.ofPropertyValuesHolder(target, pvhRotation);
rotationAnim.setDuration(5000);

View 的動畫新時代

在屬性動畫之前,View 動畫只改變「繪製方式」,View 本身的屬性並未變動,於是會出現「畫面已經移走、點擊範圍卻還在原地」的怪異行為。Android 3.0 補上了新的屬性與對應的 getter/setter:

  • translationX / translationY:在容器配置的位置(left、top)之外的位移量。
  • rotationX / rotationY:2D 與 3D 旋轉。
  • scaleX / scaleY:2D 縮放。
  • pivotX / pivotY:旋轉與縮放的中心點,預設在物件中心。
  • x / y:容器 left/top 加上 translationX/Y 的合計位置,實用屬性。
  • alpha:透明度,1 為不透明,0 為全透明。

要動畫其中任何一個,只需建立對應的屬性動畫:

ObjectAnimator.ofFloat(myView, "rotation", 0f, 360f);

ViewPropertyAnimator:更簡潔的寫法

同時動畫多個屬性時,用多個 ObjectAnimator 會相對囉嗦:

// 寫法一:多個 ObjectAnimator 組合成 AnimatorSet
ObjectAnimator animX = ObjectAnimator.ofFloat(myView, "x", 50f);
ObjectAnimator animY = ObjectAnimator.ofFloat(myView, "y", 100f);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
animSetXY.start();

// 寫法二:單一 ObjectAnimator + 多個 PropertyValuesHolder
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvhY).start();

而 ViewPropertyAnimator 一行就能搞定,並且共用底層 Animator,效率更好:

myView.animate().x(50f).y(100f);

用 XML 宣告動畫

屬性動畫的 XML 檔要放在 res/animator/(不是 res/anim/)。這樣做的好處是動畫可跨 Activity 複用,也更容易編輯序列。

對應標籤為:<animator>(ValueAnimator)、<objectAnimator>(ObjectAnimator)、<set>(AnimatorSet)。

<set android:ordering="sequentially">
    <set>
        <objectAnimator
            android:propertyName="x"
            android:duration="500"
            android:valueTo="400"
            android:valueType="intType" />
        <objectAnimator
            android:propertyName="y"
            android:duration="500"
            android:valueTo="300"
            android:valueType="intType" />
    </set>
    <objectAnimator
        android:propertyName="alpha"
        android:duration="500"
        android:valueTo="1f" />
</set>

執行時要把 XML 載入成 AnimatorSet,設定目標後啟動。setTarget() 可以一次指定所有子動畫的目標:

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext, R.animator.property_animator);
set.setTarget(myObject);
set.start();

把這幾塊拼起來看,屬性動畫的心智模型其實很單純:ValueAnimator 管時間,TimeInterpolator 管節奏,TypeEvaluator 管型別換算,ObjectAnimator 與 ViewPropertyAnimator 則負責把結果寫回物件。理解這條分工,剩下的 API 都只是排列組合。

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