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

Android 動畫入門:補間動畫(Tween Animation)完整指南

編輯:關於 Android 程式設計


本節引言

本文要談的是 Android 三種動畫中的第二種——補間動畫(Tween)。與逐幀動畫靠連續播放圖片來模擬效果不同,補間動畫只需要開發者指定起始關鍵幀與結束關鍵幀,中間的過渡幀交給系統自行計算補齊即可。


一、補間動畫的分類與 Interpolator

Android 支援的補間效果主要有以下五種,嚴格來說是四種,第五種只是前者的組合:

AlphaAnimation:透明度漸變。建立時需指定起始與結束透明度、持續時間,透明度範圍為 0(全透明)到 1(全不透明),對應 <alpha> 標籤。
ScaleAnimation:縮放漸變。需指定起始與結束縮放比、縮放參考點與持續時間,對應 <scale> 標籤。
TranslateAnimation:位移漸變。指定起點與終點座標及持續時間,對應 <translate> 標籤。
RotateAnimation:旋轉漸變。指定起始與結束角度、旋轉軸心與持續時間,對應 <rotate> 標籤。
AnimationSet:組合動畫,把上述多種效果打包在一起,對應 <set> 標籤。

在進入各動畫的細節之前,先認識 Interpolator。

Interpolator 用來控制動畫的變化速度,可以把它想成「動畫節奏控制器」。你也可以自行實作 Interpolator 介面,而 Android 已經內建了多種實作:

LinearInterpolator:全程等速。
AccelerateInterpolator:起步慢、之後逐漸加速。
AccelerateDecelerateInterpolator:頭尾慢、中段加速。
DecelerateInterpolator:起步快、之後逐漸減速。
CycleInterpolator:按正弦曲線循環播放特定次數,變化量為 Math.sin(2 * mCycles * Math.PI * input)。
AnticipateInterpolator:先往反方向退一小段再加速前進。
AnticipateOvershootInterpolator:先後退,再往前衝過頭,最後回到終值。
OvershootInterpolator:先超出終值再緩慢回落到終值。
BounceInterpolator:接近終值時出現彈跳,例如終值 100,後續數值可能依序為 85、77、70、80、90、100。

寫動畫 XML 時透過 android:interpolator 指定,值寫成 @android:anim/xxx_interpolator 的形式,本質就是把上述類名的駝峰命名換成底線,例如 AccelerateDecelerateInterpolator 對應 @android:anim/accelerate_decelerate_interpolator。


二、各類動畫屬性詳解

以下 android:duration 均為動畫持續時間,單位是毫秒。

1)AlphaAnimation(透明度漸變)

anim_alpha.xml:

<alpha xmlns:android="https://schemas.android.com/apk/res/android"
  android:duration="2000"
  android:fromAlpha="0.0"
  android:toAlpha="1.0" />

屬性說明:

fromAlpha:起始透明度
toAlpha:結束透明度
取值範圍 0~1,0 全透明、1 全不透明。

2)ScaleAnimation(縮放漸變)

anim_scale.xml:

<scale xmlns:android="https://schemas.android.com/apk/res/android"
  android:duration="2000"
  android:fromXScale="0.2" android:fromYScale="0.2"
  android:toXScale="1.5" android:toYScale="1.5"
  android:pivotX="50%" android:pivotY="50%"
  android:interpolator="@android:anim/accelerate_interpolator" />

屬性說明:

fromXScale / fromYScale:沿 X 軸/Y 軸的起始縮放比例
toXScale / toYScale:沿 X 軸/Y 軸的結束縮放比例
pivotX / pivotY:縮放基準點座標,數值代表距離自身左/上邊緣的位置。例如 50% 表示以圖形中心為基準點。

3)TranslateAnimation(位移漸變)

anim_translate.xml:

<translate xmlns:android="https://schemas.android.com/apk/res/android"
  android:duration="2000"
  android:fromXDelta="0" android:fromYDelta="0"
  android:toXDelta="200" android:toYDelta="200" />

屬性說明:

fromXDelta / fromYDelta:動畫起始位置的 X/Y 座標
toXDelta / toYDelta:動畫結束位置的 X/Y 座標

4)RotateAnimation(旋轉漸變)

anim_rotate.xml:

<rotate xmlns:android="https://schemas.android.com/apk/res/android"
  android:duration="1000"
  android:fromDegrees="0" android:toDegrees="360"
  android:pivotX="50%" android:pivotY="50%"
  android:repeatCount="1" android:repeatMode="reverse"
  android:interpolator="@android:anim/accelerate_decelerate_interpolator" />

屬性說明:

fromDegrees / toDegrees:旋轉的起始/結束角度
repeatCount:重複次數,預設 0 表示播放一次;填 3 則總共播放 4 次;填 -1 或 infinite 表示無限循環。
repeatMode:重複模式,預設 restart,僅在 repeatCount 大於 0 或為 infinite/-1 時生效;設為 reverse 則偶数次播放會反向運動。

5)AnimationSet(組合漸變)

就是把前面幾種動畫包在同一個 set 裡:

<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:toXScale="1.5" android:toYScale="1.5" android:pivotX="50%" android:pivotY="50%" />
  <rotate android:duration="1000" android:fromDegrees="0" android:toDegrees="360"
    android:repeatCount="1" android:repeatMode="reverse" />
</set>

三、動手做個範例

先來個簡單的版面 activity_main.xml:

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

MainActivity.java 同樣不複雜,只要用 AnimationUtils.loadAnimation() 載入動畫,再讓 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); break;
      case R.id.btn_scale:
        animation = AnimationUtils.loadAnimation(this, R.anim.anim_scale); break;
      case R.id.btn_tran:
        animation = AnimationUtils.loadAnimation(this, R.anim.anim_translate); break;
      case R.id.btn_rotate:
        animation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate); break;
      case R.id.btn_set:
        animation = AnimationUtils.loadAnimation(this, R.anim.anim_set); break;
    }
    img_show.startAnimation(animation);
  }
}

執行結果:

是不是有點意思?趕快去動手改改參數,或自由組合出屬於自己的酷炫效果吧。


四、動畫狀態的監聽

呼叫動畫物件的 setAnimationListener(new AnimationListener()),重寫以下三個方法即可完成監聽:

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

五、為 View 動態設定動畫

靜態做法是先 AnimationUtils.loadAnimation() 載入動畫 XML,再由 View 呼叫 startAnimation(anim)。当然你也可以直接用 Java 建立動畫物件並設定屬性,再交給 startAnimation 啟動。


六、為 Fragment 設定過場動畫

這裡要特別注意:你用的是 v4 包還是 app 包下的 Fragment,兩者支援的動畫類型不同。

可以透過 FragmentTransaction 的 setTransition(int transit) 指定標準過場動畫,可選值有:

TRANSIT_NONE:無動畫
TRANSIT_FRAGMENT_OPEN:開啟形式
TRANSIT_FRAGMENT_CLOSE:關閉形式

標準過場動畫兩邊都能用,差異在於自定義動畫的 setCustomAnimations():

app 包下的 Fragment:
setCustomAnimations(int enter, int exit, int popEnter, int popExit),分別對應加入、移除、入堆疊與出堆疊時的動畫。此處搭配的是屬性動畫(Property Animation),也就是動畫檔的根標籤必須是 <objectAnimator>、<valueAnimator>,或兩者放進同一個 <set>。

v4 包下的 Fragment:支援兩種參數形式的 setCustomAnimations()。

此處搭配的動畫類型是補間動畫(Tween),與一般 View 相同。

你可能會問,怎麼判斷對應哪一種動畫類型?其實只要翻 Fragment 原始碼中的 onCreateAnimation() 回傳值就清楚了:

v4 包:
app 包:


七、為 Activity 設定過場動畫

Activity 的過場動畫很簡單,呼叫 overridePendingTransition(int enterAnim, int exitAnim),寫在 startActivity(intent) 或 finish() 之後即可。兩個參數分別是新 Activity 進場與舊 Activity 退場的動畫。


八、實作:登入/註冊按鈕從底部彈出

執行結果:

版面檔 activity_main.xml:

<relativelayout android:background="#DDE2E3" android:layout_height="match_parent" android:layout_width="match_parent" tools:context=".MainActivity" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools">
  <linearlayout android:id="@+id/start_ctrl" android:layout_alignparentbottom="true" android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="vertical" android:visibility="gone">
    <button android:id="@+id/start_login" android:background="#F26968" android:gravity="center" android:layout_height="wrap_content" android:layout_width="match_parent" android:paddingbottom="15dp" android:paddingtop="15dp" android:text="登陸" android:textcolor="#FFFFFF" android:textsize="18sp" />
    <button android:id="@+id/start_register" android:background="#323339" android:gravity="center" android:layout_height="wrap_content" android:layout_width="match_parent" 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);

    start_ctrl.postDelayed(new Runnable() {
      @Override public void run() {
        start_ctrl.setVisibility(View.VISIBLE);
        start_ctrl.startAnimation(ctrlAnimation);
      }
    }, 2000);
  }
}

註解已經寫得夠清楚。若你對 TranslateAnimation.RELATIVE_TO_SELF 的含義有疑問,查一下官方文件即可,概念並不難。

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