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

Android Tween 補間動畫完整解析

編輯:Android 開發實例

Tween 補間動畫只需要指定開始與結束狀態,中間影格由系統補齊。Android 中常見的補間動畫包括透明度、旋轉、縮放與位移,也可以組合使用。

Animation 基本屬性

  • duration:播放時間。
  • fillAfter:是否保留結束狀態。
  • fillBefore:是否保留開始狀態。
  • interpolator:速度曲線。
  • repeatCount:重複次數。
  • repeatMode:重複模式。
  • startOffset:延遲開始。

AlphaAnimation 透明度

AlphaAnimation anim = new AlphaAnimation(1.0f, 0.5f);
anim.setDuration(2000);
anim.setRepeatCount(2);
anim.setRepeatMode(Animation.REVERSE);
anim.setFillAfter(true);
iv_anim.startAnimation(anim);

XML 寫法:

<alpha xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fillAfter="true"
    android:fromAlpha="1.0"
    android:repeatCount="2"
    android:repeatMode="reverse"
    android:toAlpha="0.5" />

RotateAnimation 旋轉

RotateAnimation anim = new RotateAnimation(
    0, 360,
    Animation.RELATIVE_TO_SELF, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(2000);
iv_anim.startAnimation(anim);

pivotX 與 pivotY 可決定旋轉中心。XML 中可用 50% 表示以自己中心為準。

ScaleAnimation 縮放

ScaleAnimation anim = new ScaleAnimation(
    0.2f, 2.0f,
    0.2f, 2.0f,
    Animation.RELATIVE_TO_SELF, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(2000);
iv_anim.startAnimation(anim);

TranslateAnimation 位移

TranslateAnimation anim = new TranslateAnimation(
    Animation.RELATIVE_TO_PARENT, 0.1f,
    Animation.RELATIVE_TO_PARENT, 0.2f,
    Animation.RELATIVE_TO_PARENT, 0.1f,
    Animation.RELATIVE_TO_PARENT, 0.2f);
anim.setDuration(2000);
iv_anim.startAnimation(anim);

AnimationSet 組合動畫

若需要同時旋轉、縮放與改變透明度,可用 AnimationSet 組合。

AnimationSet animSet = new AnimationSet(false);

RotateAnimation ra = new RotateAnimation(
    0, 360,
    Animation.RELATIVE_TO_SELF, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f);
ra.setDuration(2000);

ScaleAnimation sa = new ScaleAnimation(
    0.2f, 2.0f,
    0.2f, 2.0f,
    Animation.RELATIVE_TO_SELF, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f);
sa.setDuration(2000);

AlphaAnimation aa = new AlphaAnimation(1.0f, 0.5f);
aa.setDuration(2000);

animSet.addAnimation(ra);
animSet.addAnimation(sa);
animSet.addAnimation(aa);
iv_anim.startAnimation(animSet);

座標參照類型

  • ABSOLUTE:絕對座標。
  • RELATIVE_TO_PARENT:相對於父容器。
  • RELATIVE_TO_SELF:相對於自身。

在 XML 中,若使用 %p,通常代表相對於父容器;若使用 %,通常代表相對於自身。

Interpolator 速度曲線

Interpolator 決定動畫插入影格的速度變化。常見有:

  • LinearInterpolator:等速。
  • AccelerateInterpolator:先慢後快。
  • DecelerateInterpolator:先快後慢。
  • AccelerateDecelerateInterpolator:頭尾慢,中間快。
  • CycleInterpolator:依正弦曲線循環變化。

若沒有指定,通常會使用預設的等速行為。透過 Interpolator,可以讓動畫更自然,例如按鈕回饋、旋轉載入或轉場效果。

小結:Tween 動畫的價值在於以較低成本完成流暢的視覺變化。開發時可先決定要改變的屬性,再選擇對應 Animation 子類,最後用 Interpolator 微調節奏。

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