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

【Android】21.3 動畫入門:幀動畫、視圖動畫與屬性動畫的選擇

編輯:關於 Android 開發

【Android】21.3 動畫基本用法

分類:C#、Android、VS2015 | 建立日期:2016-03-21

一、簡介

Android 提供三種建立動畫的方式:

  • Drawable Animations——畫板動畫,也稱幀動畫(Frame Animations)。
  • View Animations——視圖動畫,也稱補間動畫(Tween Animations)。
  • Property Animations——屬性動畫,從 Android 3.0 起提供。

要注意的是:雖然三者都可用,但只要條件允許,都應優先考慮屬性動畫。另外,動畫確實能抓住目光,但濫用只會讓介面顯得雜亂,反而扣分。

1. 畫板動畫(Drawable Animations)

Drawable Animations 提供按幀播放的簡單 API,在其他技術體系中一般稱為幀動畫。它的播放效果非常接近電影或卡通:靠連續切換靜態圖片製造動態錯覺。

下圖示範的是依序播放 6 張圖片,拼出一個人跳起來的動作:

控制動畫序列的畫板資源(XML 檔)通常放在 /res/drawable 中,以 <animation-list> 作為根元素,再用 <item> 定義每一幀。

例如 /res/drawable/ch2103DrawableAnimDemo.xml:

<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/a01" android:duration="100" />
    <item android:drawable="@drawable/a02" android:duration="100" />
    <item android:drawable="@drawable/a03" android:duration="100" />
    <item android:drawable="@drawable/a04" android:duration="100" />
    <item android:drawable="@drawable/a05" android:duration="100" />
    <item android:drawable="@drawable/a06" android:duration="100" />
</animation-list>

這段動畫包含六幀,a01~a06 是圖片檔,android:duration 宣告每幀顯示的毫秒數。定義好序列之後,只要在布局檔中把 ImageView 的 src 指向這個 XML,Android 就會自動依序載入並播放。

2. 視圖動畫(View Animations)

視圖動畫(補間動畫)有四種基本表現:漸變、縮放、平移、旋轉。它能處理位置、大小、不透明度、旋轉這類簡單變化,例如讓某個 ImageView 淡入或轉個角度。

這組 API 位於 Android.View.Animation 命名空間,常用的類別有:

  • AlphaAnimation:控制不透明度變化。
  • RotateAnimation:控制旋轉。
  • ScaleAnimation:控制縮放。
  • TranslateAnimation:控制平移。
  • AnimationSet:把多個動畫屬性組成一組。

動畫定義檔一般放在 /res/anim。雖然這是較早期版本提供的 API,但因為夠簡單,至今仍然好用。

把動畫寫成 /res/anim 下的 XML 是首選做法,因為比起散落在程式碼裡,XML 更易讀也更好維護。該檔案必須以下列元素之一作為根:

  • alpha——淡入或淡出
  • rotate——旋轉
  • scale——縮放
  • translate——平移(水平或垂直)
  • set——動畫容器,可包含一個或多個動畫元素

預設情況下 Android 會同時套用 XML 中的所有動畫。若要讓它們依序發生,把 android:startOffset 設在後續元素上即可。

還可以透過插值器(Interpolator)改變速率節奏:

  • AccelerateInterpolator / DecelerateInterpolator——加快或放慢
  • BounceInterpolator——結束時反彈
  • LinearInterpolator——等速

本節範例的視圖動畫就是先把圖片沿水平與垂直方向縮放,接著逆時針旋轉 45 度並同步縮小。

3. 屬性動畫(Property Animations)

屬性動畫可以對任何物件的屬性做處理(包含 View),是首選的動畫方式,即使目標物件不可見也一樣能作用。它的靈活之處在於能把動畫邏輯封裝到不同類別中,讓程式碼更容易共用。

所有屬性動畫都透過 Animator 的子類建立:

  • ValueAnimator:整個體系中最關鍵的類別。它會自動計算屬性在動畫期間應有的數值,但不直接改寫目標,而是透過事件把新值通知給你。
  • ObjectAnimator:直接對目標物件的某個屬性做動畫。
  • AnimatorSet:動畫集合,可做到同時執行、順序執行或延時執行。

搭配使用的還有幾個評估值計算器:IntEvaluator(整數)、FloatEvaluator(浮點數)、ArgbEvaluator(顏色)。若動畫的屬性型別不是 float、int 或 Color,可以自行實作 ITypeEvaluator 介面。

(1)ValueAnimator

透過下列方法之一取得實例:ValueAnimator.OfInt、ValueAnimator.OfFloat、ValueAnimator.OfObject。

ValueAnimator animator = ValueAnimator.OfInt(0, 100);
animator.SetDuration(1000);
animator.Start();

但光這樣還不夠——動畫確實在跑,目標物件卻沒被更新,所以必須掛上事件:

MyCustomObject myObj = new MyCustomObject();
myObj.SomeIntegerValue = -1;

animator.Update += (object sender, ValueAnimator.AnimatorUpdateEventArgs e) =>
{
    int newValue = (int) e.Animation.AnimatedValue;
    // 把新值套用到被動畫的物件上
    myObj.SomeIntegerValue = newValue;
};

(2)ObjectAnimator

ObjectAnimator 是 ValueAnimator 的子類,它把計時引擎與值計算結合起來,直接指定屬性名稱即可:

MyCustomObject myObj = new MyCustomObject();
myObj.SomeIntegerValue = -1;

ObjectAnimator animator = ObjectAnimator.OfFloat(myObj, "SomeIntegerValue", 0, 100);
animator.SetDuration(1000);
animator.Start();

比起 ValueAnimator 需要自己掛事件更新,這樣寫程式碼量少很多。

二、範例

1、執行結果截圖

2、設計步驟

(1)加入圖片
在 Drawable 資料夾放入 6 張圖片(ch2103asteroid01.png ~ ch2103asteroid06.png)供幀動畫使用,再放一張 ch2103ship.png 供視圖動畫使用。

(2)加入 ch2103DrawableAnimDemo.xml

<?xml version="1.0" encoding="UTF-8" ?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/ch2103asteroid01" android:duration="100" />
    <item android:drawable="@drawable/ch2103asteroid02" android:duration="100" />
    <item android:drawable="@drawable/ch2103asteroid03" android:duration="100" />
    <item android:drawable="@drawable/ch2103asteroid04" android:duration="100" />
    <item android:drawable="@drawable/ch2103asteroid05" android:duration="100" />
    <item android:drawable="@drawable/ch2103asteroid06" android:duration="100" />
</animation-list>

(3)加入 ch2103ViewAnimDemo.xml(放在 Resources/anim)

<?xml version="1.0" encoding="utf-8" ?>
<set xmlns:android="https://schemas.android.com/apk/res/android" android:shareInterpolator="false">
    <scale android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0" android:toXScale="1.4"
        android:fromYScale="1.0" android:toYScale="0.6"
        android:pivotX="50%" android:pivotY="50%"
        android:fillEnabled="true" android:fillAfter="false"
        android:duration="700" />
    <set android:interpolator="@android:anim/accelerate_interpolator">
        <scale android:fromXScale="1.4" android:toXScale="0.0"
            android:fromYScale="0.6" android:toYScale="0.0"
            android:pivotX="50%" android:pivotY="50%"
            android:fillEnabled="true" android:fillBefore="false" android:fillAfter="true"
            android:startOffset="700" android:duration="400" />
        <rotate android:fromDegrees="0" android:toDegrees="-45"
            android:pivotX="50%" android:pivotY="50%"
            android:fillEnabled="true" android:fillBefore="false" android:fillAfter="true"
            android:startOffset="700" android:duration="400" />
    </set>
</set>

(4)加入 ch2103Main.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px" android:minHeight="25px">

    <TextView android:text="畫板動畫示例"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center" android:background="@color/myGray"
        android:layout_marginTop="5dp" />

    <ImageView android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:id="@+id/ch2103_imageView_DrawableDemo"
        android:layout_marginTop="5dp" />

    <TextView android:text="視圖動畫示例"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center" android:background="@color/myGray"
        android:layout_marginTop="5dp" />

    <ImageView android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:id="@+id/ch2103_imageView_ViewDemo"
        android:layout_marginLeft="20dp" android:layout_marginTop="5dp" />

    <Button android:text="開始"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:id="@+id/ch2103_btnViewDemoStart"
        android:layout_gravity="center" />

    <TextView android:text="屬性動畫示例(拖放滑動條觀察進度條動畫)"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center" android:background="@color/myGray"
        android:layout_marginTop="5dp" />

    <FrameLayout android:minWidth="25px" android:minHeight="35px"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:id="@+id/frameLayout1"
        android:layout_marginTop="15dp" android:layout_marginBottom="5dp">
        <MyDemos.SrcDemos.ch2103MyView
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_marginLeft="8dp" android:layout_marginRight="8dp"
            android:id="@+id/ch2103myview1" />
    </FrameLayout>

    <SeekBar android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:id="@+id/ch2103seekBar1"
        android:max="100" android:progress="50"
        android:layout_marginLeft="8dp" android:layout_marginRight="8dp"
        android:layout_marginTop="10dp" />
</LinearLayout>

(5)加入 ch2103MyView.cs——自訂一個會做屬性動畫的進度條

using System;
using Android.Content;
using Android.Views;
using Android.Graphics;
using Android.Util;
using Android.Animation;

namespace MyDemos.SrcDemos
{
    /// <summary>
    /// 演示進度條動畫控制的基本用法
    /// </summary>
    public class ch2103MyView : View
    {
        private const int DefaultHeight = 20;
        private const int DefaultWidth = 120;
        private Paint mNegativePaint;
        private double mPosition = 0.5;
        private Paint mPositivePaint;

        public ch2103MyView(Context context, IAttributeSet attrs) : this(context, attrs, 0)
        { Initialize(); }

        public ch2103MyView(Context context, IAttributeSet attrs, int defStyle)
            : base(context, attrs, defStyle)
        { Initialize(); }

        public double CurrentValue
        {
            get { return mPosition; }
            set
            {
                mPosition = Math.Max(0f, Math.Min(value, 1f));
                Invalidate();
            }
        }

        public void SetCurentValue(double value, bool animate)
        {
            if (!animate) { CurrentValue = value; return; }

            // 用 ValueAnimator 讓數值在 500ms 內平滑過渡
            ValueAnimator animator = ValueAnimator.OfFloat(
                (float)mPosition, (float)Math.Max(0f, Math.Min(value, 1f)));
            animator.SetDuration(500);
            animator.Update += (sender, e) => CurrentValue = (double)e.Animation.AnimatedValue;
            animator.Start();
        }

        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);
            float middle = canvas.Width * (float)mPosition;
            canvas.DrawPaint(mNegativePaint);
            canvas.DrawRect(0, 0, middle, canvas.Height, mPositivePaint);
        }

        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            int width = MeasureSpec.GetSize(widthMeasureSpec);
            SetMeasuredDimension(width < DefaultWidth ? DefaultWidth : width, DefaultHeight);
        }

        private void Initialize()
        {
            mPositivePaint = new Paint { AntiAlias = true, Color = Color.Rgb(0x99, 0xcc, 0) };
            mPositivePaint.SetStyle(Paint.Style.FillAndStroke);
            mNegativePaint = new Paint { AntiAlias = true, Color = Color.Rgb(0xff, 0x44, 0x44) };
            mNegativePaint.SetStyle(Paint.Style.FillAndStroke);
        }
    }
}

(6)加入 ch2103MainActivity.cs

using Android.App;
using Android.OS;
using Android.Widget;
using Android.Views.Animations;

namespace MyDemos.SrcDemos
{
    [Activity(Label = "【例21-3】動畫基本用法")]
    public class ch2103MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ch2103Main);

            // 畫板動畫 Demo:直接把 animation-list 設為圖片來源即可播放
            var img1 = FindViewById<ImageView>(Resource.Id.ch2103_imageView_DrawableDemo);
            img1.SetImageResource(Resource.Drawable.ch2103DrawableAnimDemo);

            // 視圖動畫 Demo:按下按鈕才載入並套用動畫
            var btn1 = FindViewById<Button>(Resource.Id.ch2103_btnViewDemoStart);
            btn1.Click += (sender, args) =>
            {
                Animation animation = AnimationUtils.LoadAnimation(this, Resource.Animation.ch2103ViewAnimDemo);
                var img2 = FindViewById<ImageView>(Resource.Id.ch2103_imageView_ViewDemo);
                img2.SetImageResource(Resource.Drawable.ch2103ship);
                img2.StartAnimation(animation);
            };

            // 屬性動畫 Demo:拖動 SeekBar 觀察進度條平滑過渡
            var myView = FindViewById<ch2103MyView>(Resource.Id.ch2103myview1);
            var seekBar = FindViewById<SeekBar>(Resource.Id.ch2103seekBar1);
            seekBar.StopTrackingTouch += (sender, args) =>
            {
                double currentValue = ((double)seekBar.Progress) / seekBar.Max;
                myView.SetCurentValue(currentValue, true);
            };
        }
    }
}

三種動畫的取捨可以這樣記:要播放一串圖片就用幀動畫;要讓既有 View 做簡單的位置、大小、透明度變化,視圖動畫寫 XML 最省事;需要真正改動物件屬性、或要做複雜的連動與交錯,就該用屬性動畫。

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