Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

8.4.2 補間動畫全解:四種漸變、九種補間器與過場動畫

編輯:Android 技術基礎

本節導讀

本節談 Android 三種動畫中的第二種——補間動畫(Tween Animation)。

它與前一節的 frame 動畫思路完全不同:frame 動畫靠連續播放一張張圖片來「演」出動作;補間動畫則是開發者只需指定動畫的起點與終點這兩個關鍵影格,中間的過渡影格由系統計算補齊——這也是「補間」二字的由來。


一、五種補間動畫與 Interpolator

嚴格說是四種基本動畫加上一種組合:

  • AlphaAnimation:透明度漸變。建立時指定起始與結束透明度(0 = 全透明,1 = 完全不透明)與持續時間。對應 <alpha> 標籤。
  • ScaleAnimation:縮放漸變。需指定 X/Y 軸的起始與結束比例、縮放中心點、持續時間。對應 <scale> 標籤。
  • TranslateAnimation:位移漸變。指定起始與結束座標、持續時間。對應 <translate> 標籤。
  • RotateAnimation:旋轉漸變。指定起始與結束角度、旋轉軸心、持續時間。對應 <rotate> 標籤。
  • AnimationSet:組合漸變,把上面幾種打包一起跑。對應 <set> 標籤。

Interpolator:動畫的速度曲線

動手寫之前先認識 Interpolator。它決定「同一段時長內,畫面變化得快還是慢」,可以理解為動畫的變化率控制器。你也可以自行實作 Interpolator 介面,但 Android 已內建九種常見實作:

  • LinearInterpolator:等速變化。
  • AccelerateInterpolator:起步慢,之後逐漸加速。
  • DecelerateInterpolator:起步快,之後逐漸減速。
  • AccelerateDecelerateInterpolator:起步與收尾都慢,中段最快。
  • CycleInterpolator:循環播放指定次數,速度依正弦曲線變化:Math.sin(2 * mCycles * Math.PI * input)。
  • AnticipateInterpolator:先往反方向退一小段,再加速前進(蓄勢的效果)。
  • OvershootInterpolator:先衝過目標值,再回彈到終點。
  • AnticipateOvershootInterpolator:兩者結合,先退再衝過頭再回來。
  • BounceInterpolator:接近終點時反覆跳動,像球落地後的彈跳。

在 XML 中使用時,屬性名為 android:interpolator,取值就是把類別名從駝峰改為底線並加上 @android:anim/ 前綴。例如 AccelerateDecelerateInterpolator 對應 @android:anim/accelerate_decelerate_interpolator。


二、四種動畫的屬性詳解

以下所有範例中的 android:duration 單位皆為毫秒。

1. AlphaAnimation(透明度漸變)

anim_alpha.xml:

<alpha xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fromAlpha="1.0"
    android:toAlpha="0.1"
    android:duration="2000"/>

fromAlpha 為起始透明度、toAlpha 為結束透明度,範圍 0~1。上例的效果是「從不透明漸漸淡出到幾乎透明」。

2. ScaleAnimation(縮放漸變)

anim_scale.xml:

<scale xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromXScale="0.2"
    android:toXScale="1.5"
    android:fromYScale="0.2"
    android:toYScale="1.5"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="2000"/>
  • fromXScale / fromYScale:沿 X/Y 軸的起始縮放比例。
  • toXScale / toYScale:沿 X/Y 軸的結束縮放比例。
  • pivotX / pivotY:縮放中心點座標,是相對於自身左上角(或父容器)的距離。50% 就是以自身中心為軸,寫 0 或 0% 則是以左上角為軸——這個參數寫錯是「縮放方向怪怪的」最常見原因。

3. TranslateAnimation(位移漸變)

anim_translate.xml:

<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fromXDelta="0"
    android:toXDelta="320"
    android:fromYDelta="0"
    android:toYDelta="0"
    android:duration="2000"/>
  • fromXDelta / fromYDelta:起始位置的 X/Y 位移量。
  • toXDelta / toYDelta:結束位置的 X/Y 位移量。

這些值除了絕對像素,還能用 0%(自身寬高的百分比)或 100%p(父容器寬高的百分比)等相對寫法,做響應式動畫時很方便。

4. RotateAnimation(旋轉漸變)

anim_rotate.xml:

<rotate xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:duration="1000"
    android:repeatCount="1"
    android:repeatMode="reverse"/>
  • fromDegrees / toDegrees:起始與結束角度。
  • repeatCount:重複次數,預設 0(播放一輪)。設為 3 代表總共播放 4 次;設為 -1 或 infinite 則無限循環。
  • repeatMode:重複模式,預設 restart(每次都從頭跑);設為 reverse 則隔次反向播放,形成來回擺動的效果。此屬性僅在 repeatCount 大於 0 或為 infinite 時才有效。

5. AnimationSet(組合漸變)

anim_set.xml:

<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:shareInterpolator="true" >
    <scale
        android:duration="2000"
        android:fromXScale="0.2"
        android:fromYScale="0.2"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.5"
        android:toYScale="1.5" />
    <rotate
        android:duration="1000"
        android:fromDegrees="0"
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:toDegrees="360" />
    <translate
        android:duration="2000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:toXDelta="320"
        android:toYDelta="0" />
    <alpha
        android:duration="2000"
        android:fromAlpha="1.0"
        android:toAlpha="0.1" />
</set>

shareInterpolator 決定子動畫是否共用 set 上設定的補間器。設為 false 時,每個子動畫可以各自指定自己的 interpolator。


三、動手做:五種動畫逐一觸發

activity_main.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button android:id="@+id/btn_alpha" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="透明度漸變" />
    <Button android:id="@+id/btn_scale" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="縮放漸變" />
    <Button android:id="@+id/btn_tran" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="位移漸變" />
    <Button android:id="@+id/btn_rotate" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="旋轉漸變" />
    <Button android:id="@+id/btn_set" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="組合漸變" />
    <ImageView android:id="@+id/img_show" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="center"
        android:layout_marginTop="48dp" android:src="@mipmap/img_face" />
</LinearLayout>

MainActivity.java:用 AnimationUtils.loadAnimation() 載入 XML,再交給 View 的 startAnimation() 播放。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_alpha, btn_scale, btn_tran, btn_rotate, btn_set;
    private ImageView img_show;
    private Animation animation = null;

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

    private void bindViews() {
        btn_alpha = (Button) findViewById(R.id.btn_alpha);
        btn_scale = (Button) findViewById(R.id.btn_scale);
        btn_tran = (Button) findViewById(R.id.btn_tran);
        btn_rotate = (Button) findViewById(R.id.btn_rotate);
        btn_set = (Button) findViewById(R.id.btn_set);
        img_show = (ImageView) findViewById(R.id.img_show);
        btn_alpha.setOnClickListener(this);
        btn_scale.setOnClickListener(this);
        btn_tran.setOnClickListener(this);
        btn_rotate.setOnClickListener(this);
        btn_set.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_alpha:
                animation = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
                img_show.startAnimation(animation);
                break;
            case R.id.btn_scale:
                animation = AnimationUtils.loadAnimation(this, R.anim.anim_scale);
                img_show.startAnimation(animation);
                break;
            case R.id.btn_tran:
                animation = AnimationUtils.loadAnimation(this, R.anim.anim_translate);
                img_show.startAnimation(animation);
                break;
            case R.id.btn_rotate:
                animation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
                img_show.startAnimation(animation);
                break;
            case R.id.btn_set:
                animation = AnimationUtils.loadAnimation(this, R.anim.anim_set);
                img_show.startAnimation(animation);
                break;
        }
    }
}

接下來就換你玩了——改改參數、自由組合,做出一組屬於自己的轉場效果。

一個容易忽略的細節:補間動畫不會改變 View 的真實屬性。位移動畫跑完之後,View 會「跳回」原位,而且它的實際點擊區域仍留在原本的位置。若需要真正改變位置或大小,應該改用屬性動畫(下一節的主題)。


四、監聽動畫狀態

呼叫動畫物件的 setAnimationListener(new AnimationListener()),覆寫以下三個方法:

  • onAnimationStart():動畫開始
  • onAnimationRepeat():動畫重複
  • onAnimationEnd():動畫結束

五、動態為 View 設定動畫

靜態做法是 AnimationUtils.loadAnimation() 讀 XML 再 startAnimation(anim)。若想完全用 Java 動態建立,則直接 new 出對應的 Animation 子類(如 TranslateAnimation)設定參數,一樣呼叫 startAnimation() 即可。


六、為 Fragment 設定過場動畫

這裡有個關鍵差異:Fragment 是來自 v4 套件還是 app 套件,支援的動畫類型不同。

通用的做法是呼叫 FragmentTransaction.setTransition(int transit) 使用系統標準過場:

  • TRANSIT_NONE:無動畫
  • TRANSIT_FRAGMENT_OPEN:展開時的動畫
  • TRANSIT_FRAGMENT_CLOSE:關閉時的動畫

自訂動畫則靠 setCustomAnimations():

app 套件的 Fragment:

setCustomAnimations(int enter, int exit, int popEnter, int popExit)

四個參數分別對應「加入、移除、入返回堆疊、出返回堆疊」四個時機。注意這裡的動畫類型是屬性動畫,也就是 XML 根標籤必須是 <objectAnimator>、<valueAnimator>,或包在 <set> 裡。

v4 套件的 Fragment:支援兩種多載。

而 v4 這邊對應的動畫類型是補間動畫,用法與一般 View 相同。

怎麼確認?直接翻 Fragment 原始碼裡 onCreateAnimation() 的回傳型別就知道了:

v4 套件:

app 套件:


七、為 Activity 設定過場動畫

API 只有一個:overridePendingTransition(int enterAnim, int exitAnim),在 startActivity(intent) 或 finish() 之後呼叫。

兩個參數分別是「新 Activity 進場」與「舊 Activity 退場」的動畫資源。

下載:Activity常用過渡動畫.zip


八、綜合範例:登入/註冊按鈕自底部滑出

activity_main.xml:

<RelativeLayout 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:background="#DDE2E3"
    tools:context=".MainActivity">
    <LinearLayout
        android:id="@+id/start_ctrl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical"
        android:visibility="gone">
        <Button
            android:id="@+id/start_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#F26968"
            android:gravity="center"
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:text="登入"
            android:textColor="#FFFFFF"
            android:textSize="18sp" />
        <Button
            android:id="@+id/start_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#323339"
            android:gravity="center"
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:text="註冊"
            android:textColor="#FFFFFF"
            android:textSize="18sp" />
    </LinearLayout>
</RelativeLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity {
    private LinearLayout start_ctrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start_ctrl = (LinearLayout) findViewById(R.id.start_ctrl);

        // 從自身底部往上滑出自身的高度,耗時 500ms
        final TranslateAnimation ctrlAnimation = new TranslateAnimation(
                TranslateAnimation.RELATIVE_TO_SELF, 0,
                TranslateAnimation.RELATIVE_TO_SELF, 0,
                TranslateAnimation.RELATIVE_TO_SELF, 1,
                TranslateAnimation.RELATIVE_TO_SELF, 0);
        ctrlAnimation.setDuration(500l);

        // 延遲 2 秒後顯示並播放動畫
        start_ctrl.postDelayed(new Runnable() {
            @Override
            public void run() {
                start_ctrl.setVisibility(View.VISIBLE);
                start_ctrl.startAnimation(ctrlAnimation);
            }
        }, 2000);
    }
}

這裡的四組參數是「fromX 型別, fromX 值, toX 型別, toX 值, fromY 型別, fromY 值, toY 型別, toY 值」。Y 從 RELATIVE_TO_SELF, 1(自身高度的 100%,也就是完全在下方)移到 RELATIVE_TO_SELF, 0(原位),就成了由下滑入的樣子。

小提醒:因為 visibility 初始為 gone,若直接 startAnimation 是看不到效果的,所以範例用 postDelayed 在設為 VISIBLE 之後才播放。


本節回顧

補間動畫的學習重點可以濃縮成三件事:四種基本動畫各自的參數含義(特別是 pivot 與相對座標的百分比寫法)、Interpolator 決定速度曲線、AnimationSet 組合多種效果。再加上 AnimationListener 的狀態回呼,以及為 View/Fragment/Activity 掛動畫的三種 API,就足以應付絕大多數的過場需求。

但也要記住它的本質限制:補間動畫是「視覺上的變換」,View 的真實屬性並未改變。若動畫結束後版面狀態需要跟著改變,就該轉往下一節的屬性動畫。

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