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

Day34 - Animation 動畫:補間、逐幀與屬性動畫一次講透

編輯:關於 Android 程式設計

人眼存在視覺殘留現象,連續播放一系列靜態圖像,就會形成動畫效果。Android 中的動畫大致分為三類:

· 遊戲動畫:利用自訂 View 的繪製方法,開啟執行緒高頻刷新介面;
· 視圖動畫(View Animation):針對 View 及其子類,包含補間動畫與逐幀動畫;
· 屬性動畫(Property Animation):針對物件屬性,絕大多數場景也可以用來操作 View。

補間動畫

Android 依據起始狀態與結束狀態,對控件做移動、旋轉、縮放等顯示效果上的變化,从而形成動畫。

兩種實現方式

XML 定義(官方推薦):檔案放在 res/anim/ 目錄下,透過 AnimationUtils 載入。

程式碼實現:可擴展性相對較差,適合簡單場景。

核心思想是:指定開始狀態與結束狀態,由 Android 系統在兩者之間自動填充中間影格,形成連續動畫。

特點

· 透過指定時間、起始狀態、結束狀態,由系統 API 呈現動態效果;
· 動畫播放完畢後,控件會還原為原始的位置與狀態;
· 可以透過監聽器掌握動畫的開始、循環、結束;
· 動畫播放期間若再次設定動畫,當前動畫會被終止。

插值器:動畫為何看起來「順」

系統會依據插值器(interpolator),在每一段等分的時間區間內設定不同的數值比例,從而讓動畫呈現出先快後慢、先慢後快、彈跳等不同節奏。

組合與串接

在 set 標籤中寫入多個動畫即可組合播放。若希望動畫串行執行,需要透過 startOffset 把後續動畫的起始時間往後延。

要注意的是,補間動畫的 set 有點像執行緒池:內部每個動畫效果實際上獨立推進,所以即使某個效果設為無限循環,其他效果仍能正常執行。

最重要的一句話

!!!任何動畫操作都不會影響控件的真實狀態。補間動畫只是對控件外觀做了各種處理,控件本身仍在原來的位置、仍是原來的大小。理解這一點,很多「動畫跑完點擊位置卻對不上」的問題就都能解釋了。若想讓視覺狀態與真實狀態一致,可以嘗試 translate + rotate 的組合來還原。

使用方式:透過 AnimationUtils.loadAnimation 載入,再呼叫 View#startAnimation(Animation) 播放。

動畫監聽

AnimationListener 提供三個回調:onAnimationStart(開始)、onAnimationEnd(結束)、onAnimationRepeat(重複)。

幾種動畫效果

XML 檔案放在 res/anim/ 下。

旋轉:

<!-- android:repeatCount="infinite" 無限循環
     android:interpolator="@android:interpolator/linear" 線性插值,可平滑旋轉 -->
<rotate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite" />

縮放:必須同時設定 x 與 y 的縮放比例,若不設定則預設為 0 -> 0。

<scale xmlns:android="https://schemas.android.com/apk/res/android"
    android:fromXScale="1"
    android:fromYScale="1"
    android:toXScale="2"
    android:toYScale="2"
    android:pivotX="50%"
    android:pivotY="50%" />

組合集合:

<!-- 動畫定義的集合,使用 set 包含多個動畫
     duration: 持續時間
     Delta: 增量
     startOffset: 當前效果在動畫啟動多久之後執行
     注意 Android 座標系的原點在左上角 -->
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 所有動畫效果都需要設定 duration 屬性 -->
</set>

對應的 Java 程式碼:

public void btnRotateClick(View view) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
    animation.setRepeatMode(Animation.INFINITE);
    animation.setInterpolator(new LinearInterpolator());   // 平滑旋轉
    view.startAnimation(animation);
}

public void btMoveInterpolator(View view) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_move);
    animation.setDuration(1000);
    animation.setInterpolator(new OvershootInterpolator(20));
    view.startAnimation(animation);
}

public void btnScale(View view) {
    ImageView imageView = (ImageView) findViewById(R.id.image_view);
    if (imageView != null) {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_heartbeat);
        animation.setDuration(1000);
        AnimationSet animationSet = (AnimationSet) animation;
        List<Animation> animations = animationSet.getAnimations();
        Animation anim = animations.get(0);
        anim.setRepeatMode(Animation.REVERSE);
        anim.setRepeatCount(Animation.INFINITE);
        imageView.startAnimation(animation);
    }
}

// 動畫監聽
animation.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) {
        tvInc.setVisibility(View.INVISIBLE);
        tvZan.setText("贊" + zanCount);
    }

    @Override
    public void onAnimationRepeat(Animation animation) { }
});

逐幀動畫

逐幀動畫的本質是一個 Drawable,可以視為一組圖片,和 shape 一樣用 XML 描述。系統會依 XML 中的順序載入圖片,最上面的最先顯示。

可以透過 oneshot 屬性控制動畫是否只播放一次。設為 true 時只播一遍,且即使播放結束,狀態仍是 running;此時直接呼叫 start() 不會有效果,必須先 stop() 才能重新 start()。

使用步驟

1. 準備圖片資源;
2. 在 drawable 中編寫 XML,指定每一幀的圖片與持續時間;
3. 把該資源設為 ImageView 或其他 View 的 background;
4. 程式碼中取得 ImageView,取出 background,判斷是否為 AnimationDrawable 並強制轉型;
5. 呼叫 start() / stop() 控制播放。注意 start() 不支援續播,每次都從頭開始。

適用場景

重複性、帶動畫效果的提示內容,例如京東客戶端下拉刷新時「快遞小哥」的動畫;以及一些不適合用補間動畫表達的細緻動態效果。它通常與具體事件配合,如下拉刷新、圓形進度條。

程式碼示例

<!-- 逐幀動畫:在指定時間內依次顯示每一張圖片
     android:oneshot="true" 控制是否只播放一次 -->
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@mipmap/d00" android:duration="200" />
    <item android:drawable="@mipmap/d01" android:duration="200" />
    <!-- ... -->
    <item android:drawable="@mipmap/d09" android:duration="200" />
</animation-list>
public void btnPlayFrame(View view) {
    // 逐幀動畫是 Drawable,要從 ImageView 中取出才能控制
    ImageView imageGift = (ImageView) findViewById(R.id.image_gift);
    Drawable drawable = imageGift.getDrawable();
    // shape -> ShapeDrawable;animation-list -> AnimationDrawable
    if (drawable != null && drawable instanceof AnimationDrawable) {
        AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
        animationDrawable.start();
    }
}

public void btnStopFrame(View view) {
    ImageView imageGift = (ImageView) findViewById(R.id.image_gift);
    Drawable drawable = imageGift.getDrawable();
    if (drawable != null && drawable instanceof AnimationDrawable) {
        AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
        // stop 只是停止,下次 start 仍會從頭播放
        animationDrawable.stop();
    }
    // 若要播放 GIF,可使用 GifDrawable 庫或 WebView
}

屬性動畫

屬性動畫定義在 res/animator/ 資源目錄下,實現的是按時間改變控件的屬性值。與補間動畫最大的差別在於:它真正改變控件的屬性,會觸發重新排版,而且動畫結束後不會還原。

objectAnimator 標記

它能以動畫方式修改任意物件的屬性,透過自動呼叫 setXxxx 這類方法來修改屬性「xxxx」。使用時需要指定屬性名稱。

執行原理

關鍵環節包括:AnimatorSet 的組合、Interpolator 對時間比例的控制、setTarget(Target) 指定作用對象,以及 valueFrom / valueTo 界定數值區間。最後透過 setter(例如 setTranslationX)把計算出的值套用到物件上。

實現步驟

1. 準備屬性動畫的 XML 資源;
2. 準備需要播放動畫的物件;
3. 用 AnimatorInflater 載入 XML;
4. 呼叫 setTarget 指定目標;
5. 屬性名稱必須對應 Java 類中 public void setXxxxx(...) 方法的 xxxx 部分,且首字母小寫。

Target 的設定

最常見的是直接以 View 為目標,修改 color、dimension、int、float 等屬性。屬性動畫也可以指定非 View 的物件:官方推薦的做法是定義自訂 Object,在它的 setXxxx() 內部實作更強大的邏輯,然後把動畫目標設為該物件。

動畫執行序列

set 標籤可透過 ordering 屬性設定內部動畫的執行方式:sequentially 為串行,一個執行完再執行下一個(此時要避免無限重複,否則後續動畫無法執行);together 為並行同時執行。

低版本相容

ViewCompat 提供了 View 狀態設定的相容方法,例如 ViewCompat.setScaleX(View, float) 可縮放控件水平方向尺寸;ViewPropertyAnimatorCompat 支援在低版本手機上實現屬性動畫;ViewCompat.animate(View) 則為 View 建立一個屬性動畫物件。

動畫與手勢事件的配合

ScrollView 的 onTouch MOVE 事件可以與控件的隱藏/顯示效果搭配;ListView 的 OnScrollListener 能監聽滾動過程,從而在滑動時實現圖片或標題的縮放。

程式碼實例

<!-- 屬性修改器:在指定時間內把屬性從一個數值變換到另一個數值
     對應 setTranslationX(float x) -->
<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:propertyName="translationX"
    android:valueFrom="0"
    android:valueTo="400"
    android:duration="2000" />
public void btnPropertyMove(View view) {
    Animator animator = AnimatorInflater.loadAnimator(this, R.animator.animator_move);
    animator.setTarget(mTextView);
    animator.start();
}

public void btnPropertyCustom(View view) {
    // 自定義物件的屬性修改
    TextShower shower = new TextShower(mTextView);       // 1. 自定義類物件
    Animator animator = AnimatorInflater.loadAnimator(this, R.animator.anmiator_text_show);
    animator.setTarget(shower);                          // 3. 設定目標
    animator.start();
}

public void btnPropertyCode(View view) {
    // 純程式碼形式的屬性動畫,位置相關數值以像素為單位
    // ObjectAnimator.ofFloat(mTextView, "translationX", 0, 200)
    //         .setDuration(2000).start();

    // 利用 AnimatorSet 同時修改多個屬性
    AnimatorSet set = new AnimatorSet();
    ObjectAnimator animator1 = ObjectAnimator.ofFloat(mTextView, "translationX", 0, 400)
            .setDuration(2000);
    ObjectAnimator animator2 = ObjectAnimator.ofFloat(mTextView, "rotation", 0, 360)
            .setDuration(200);
    set.playTogether(animator1, animator2);
    set.start();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved