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

Android 動畫深入解析:View 動畫、幀動畫與屬性動畫全觀

編輯:關於 Android 開發

Android 動畫深入分析(閱讀筆記整理)

Android 的動畫體系可以切成三大類:View 動畫、幀動畫與屬性動畫。其中幀動畫在分類上歸屬於 View 動畫,是 View 動畫的一種特殊形式。

7.1 View 動畫

作用對象是 View,提供四種基本效果:

名稱標籤對應子類效果
平移<translate>TranslateAnimation移動 View 位置
縮放<scale>ScaleAnimation放大或縮小 View
旋轉<rotate>RotateAnimation旋轉 View
透明度<alpha>AlphaAnimation改變 View 透明度

檔案位置為 res/anim/filename.xml,語法大致如下:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@anim/interpolator_resource"
    android:shareInterpolator="true|false">

    <alpha android:fromAlpha="float" android:toAlpha="float" />

    <scale android:fromXScale="float" android:toXScale="float"
           android:fromYScale="float" android:toYScale="float"
           android:pivotX="float" android:pivotY="float" />

    <translate android:fromXDelta="float" android:fromYDelta="float"
               android:toXDelta="float" android:toYDelta="float" />

    <rotate android:fromDegrees="float" android:toDegrees="float"
            android:pivotX="float" android:pivotY="float" />

    <set> ... </set>
</set>

幾個關鍵屬性:

  • <set> 代表動畫集合,對應 AnimationSet,內部可以再嵌套集合。
  • android:interpolator 決定動畫的速度曲線,預設為加速減速插值器。
  • android:shareInterpolator 集合中的動畫是否共用同一個插值器。
  • android:duration 動畫持續時間(毫秒)。
  • android:fillAfter 動畫結束後是否停留在終點位置。
  • 縮放與旋轉的軸心點 pivotX/pivotY 若不指定,預設以 View 中心為基準。

在程式碼中載入並啟動:

Animation animation = AnimationUtils.loadAnimation(this, R.anim.view1);
button.startAnimation(animation);

需要監聽動畫狀態時,透過 animation.setAnimationListener(...) 即可。

自定義 View 動畫

做法是繼承抽象類 Animation,覆寫 initialize() 做初始化、覆寫 applyTransformation() 執行矩陣變換。實務上通常搭配 Camera 簡化矩陣運算,例如 API Demos 中的 Rotate3dAnimation 就是很好的參考範例。一句話總結:自定義 View 動畫的本質就是矩陣變換。

幀動畫

幀動畫就是依序播放預先準備好的一組圖片,由 AnimationDrawable 驅動:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="true|false">
    <item android:drawable="@mipmap/ic_launcher" android:duration="500" />
    <item android:drawable="@mipmap/ic_launcher" android:duration="500" />
    <item android:drawable="@mipmap/ic_launcher" android:duration="500" />
</animation-list>

使用時把它設為 View 背景,再取得 Drawable 播放:

button.setBackgroundResource(R.drawable.view2);
AnimationDrawable drawable = (AnimationDrawable) button.getBackground();
drawable.start();

注意幀動畫會把所有影格一次載入記憶體,影格過大或過多時容易觸發 OOM。

7.2 View 動畫的特殊應用場景

LayoutAnimation

作用於 ViewGroup:指定一個動畫後,其所有子元素進場時都會套用該效果。三步驟:

(1)定義 LayoutAnimation:

<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="0.5"
    android:animationOrder="normal"
    android:animation="@anim/anim_item" />

android:delay 是子元素之間的啟動延遲比例;若子動畫時長 200ms,0.5 代表每個元素遞延 100ms 啟動。android:animationOrder 則有 normal(順序)、reverse(逆序)、random(隨機)三種。

(2)為子元素定義動畫:

<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="300"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:shareInterpolator="true">
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" />
    <translate android:fromXDelta="500" android:toYDelta="0" />
</set>

(3)在 ViewGroup 上掛上 android:layoutAnimation="@anim/anim_layout",或用程式碼建立控制器:

Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_item);
LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.5f);
controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
linearLayout.setLayoutAnimation(controller);

Activity 切換動畫

使用 overridePendingTransition(enterAnim, exitAnim),此方法必須在 startActivity() 或 finish() 之後呼叫才會生效。enterAnim 是新頁面進入的動畫,exitAnim 是舊頁面離開的動畫。

Intent intent = new Intent(this, TestActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);

@Override
public void finish() {
    super.finish();
    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
}

7.3 屬性動畫

需 API Level 11 以上,資源置於 res/animator/。相較 View 動畫只能作用在 View 上,屬性動畫能對任意物件的屬性做動畫,核心類別是 ValueAnimator 與 ObjectAnimator。預設時長 300ms、預設約每 10ms 一幀。若要相容低版本系統,可引入 NineOldAndroids 這類開源庫。

// 讓物件沿 Y 軸上移自身高度的距離
ObjectAnimator.ofFloat(myObject, "translationY", -myObject.getHeight());

// 背景色漸變:3 秒內從 0xFFFF8080 過渡到 0xFF8080FF,無限循環並反向播放
ValueAnimator colorAnim = ObjectAnimator.ofInt(this, "backgroundColor", 0xFFFF8080, 0xFF8080FF);
colorAnim.setDuration(3000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();

XML 寫法:

<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:ordering="sequentially|together">
    <objectAnimator
        android:duration="int"
        android:propertyName="string"
        android:repeatCount="int"
        android:repeatMode="restart|reverse"
        android:startOffset="int"
        android:valueFrom="float|int|color"
        android:valueTo="float|int|color"
        android:valueType="colorType|intType|floatType|pathType" />
    <animator ... />
</set>

ordering 的 together 表示子動畫同時播放,sequentially 則依序播放;repeatCount 為 -1 代表無限循環;repeatMode 的 reverse 會在第二輪倒著播、第三輪再正向播放。

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(context, R.anim.property_animator);
set.setTarget(button);
set.start();

實務建議:屬性動畫優先用程式碼撰寫,XML 方式在動態計算與除錯上都不方便。

插值器與估值器

  • 插值器(Interpolator):依時間流逝的百分比,算出目前屬性變化的百分比。
  • 估值器(Evaluator):依變化的百分比,算出對應的實際屬性值。

監聽器

  • AnimatorListener:監聽動畫的 start、end、cancel、repeat。
  • AnimatorUpdateListener:監聽整個動畫過程中的每一幀更新。

對任意屬性做動畫的兩個前提

  1. 目標物件必須提供 setAbc();若動畫未指定初始值,還必須提供 getAbc(),否則程式直接崩潰。
  2. setAbc() 對屬性造成的改變,必須能以某種方式呈現出來(例如反映到 UI),否則動畫等於沒有視覺效果。

原理上,屬性動畫會依你給的起始值與結束值,隨時間推移不斷呼叫 setAbc(),每次傳入的值都越來越接近終值;若未提供起始值,系統就會回頭呼叫 getter 取得。

7.4 使用動畫的注意事項

View 動畫改變的是 View 的「影像」,並未真正改變 View 狀態。因此常出現動畫結束後 setVisibility(View.GONE) 失效的情況,解法是呼叫 view.clearAnimation() 清掉殘留動畫。

另一個經典陷阱是點擊事件的命中位置:在 Android 3.0 以前,無論 View 動畫或屬性動畫,移動後的新位置都無法觸發點擊,原本的位置反而仍然有效。從 3.0 起,屬性動畫的點擊命中會跟著移動到新位置,但 View 動畫仍停留在原位置。理解這點能省下大量「明明看得到卻點不到」的排查時間。

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