《Android 開發(fā)藝術探索》筆記9--Andriod動畫深入分析

Andriod動畫深入分析.png

View動畫

View動畫作用的對象是View, 它支持四種動畫效果平移, 縮放, 旋轉(zhuǎn), 透明. 除了這四種典型的變化效果. 幀動畫也屬于View動畫.

View動畫的種類

View動畫的四種變換效果對應著Animation的四個子類:TranslateAnimation, ScaleAnimation, RotateAnimationAlphaAnimation.

對于View動畫建議采用XML來定義動畫

名稱 標簽 子類 效果
平移動畫 <translate> TranslateAnimation 移動View
縮放動畫 <scale> ScaleAnimation 放大或者縮小View
旋轉(zhuǎn)動畫 <rotate> RotateAnimation 旋轉(zhuǎn)View
透明度動畫 <alpha> AlphaAnimation 改變View的透明度

創(chuàng)建的動畫的xml文件. 是放在res/anim這個文件夾下的. View動畫描述文件的固有語法如下

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"

    android:shareInterpolator="true"

    android:fillAfter="true">

    <alpha 

        android:fromAlpha="float"

        android:toAlpha="float"/>

    <scale

        android:fromXScale="float"

        android:toXScale="float"

        android:fromYScale="float"

        android:toYScale="float"

        android:pivotX="float"

        android:pivotY="float"/>

    <translate

        android:fromXDelta="float"

        android:toXDelta="float"

        android:fromYDelta="float"

        android:toYDelta="float"/>

    <rotate

        android:fromDegrees="float"

        android:toDegrees="float"

        android:pivotY="float"

        android:pivotX="float"/>

</set>

關于動畫我們可以只設置一種也可以設置多種的組合.

set標簽對應著AnimationSet類, 標簽中的屬性的意義:

  • shareInterpolator 表示集合中的動畫是否和集合共享一個插值器. 如果集合不指定插值器, 那么子動畫就需要單獨制定所需的插值器或者使用默認值
  • fillAfter 是否保留動畫結束之后的狀態(tài)

translate標簽表示平移動畫, 對應著TranslateAnimation

屬性值的意義就是from開頭的為開始起點, to開頭的結束點

scale標簽表示縮放動畫, 對應著ScaleAnimation

屬性值的意思from開頭的表示開始時原圖縮放的百分比. 用浮點數(shù)表示1表示100%(無變化),0.5表示50%(原來的一般), 2表示200%(原來的兩倍). to開頭的表示結束時的百分比. pivot表示縮放的軸點.

rotate標簽表示旋轉(zhuǎn)動畫, 對應著RotateAnimation

fromDegrees旋轉(zhuǎn)的開始角度, toDegrees旋轉(zhuǎn)的結束角度. pivot旋轉(zhuǎn)的軸點

alpha標簽表示透明度動畫, 對應AlphaAnimation

fromAlpha表示透明度的起始值, toAlpha表示透明度的結束值.

上面這些標簽還有一些通用的屬性值. 例如duration執(zhí)行時間.

xml如果聲明了之后那么我們就該在代碼中應用了. 如下:

View btn_main = findViewById(R.id.parent);

Animation animation = AnimationUtils.loadAnimation(this, R.anim.temp);

btn_main.startAnimation(animation);

同樣也可以不需要xml直接在代碼中生成動畫對象.

AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);

alphaAnimation.setDuration(1000);

btn_main.startAnimation(alphaAnimation);

在開始動畫之前可以給動畫添加一個監(jiān)聽setAnimationListener()這樣在動畫開始結束和每一次循環(huán)下一次的時候都可以在回調(diào)方法中監(jiān)聽到.

自定義View動畫

如果需要自定義View動畫, 首先應該繼承Animation這個抽象類來派生出一種新動畫. 然后重寫initialize()applyTransformation()方法. 在initialize中做一些初始化動作, 在applyTransformation()中進行相應矩陣變換, 很多時候需要采用Camera來簡化矩陣變換的過程. 而View動畫變化主要就是矩陣的變換過程.

幀動畫

幀動畫是順序播放一組預先定義好的圖片, 類似于電影. 系統(tǒng)提供了AnimationDrawable來使用幀動畫.

同樣在xml中聲明, 在res/drawable/包下創(chuàng)建文件, 并替換每個drawable圖片即可

<?xml version="1.0" encoding="utf-8"?>

<animation-list

    xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"

    android:oneshot="false">

    <item android:drawable="@drawable/xx1" android:duration="500"/>

    <item android:drawable="@drawable/xx2" android:duration="500"/>

    <item android:drawable="@drawable/xx3" android:duration="500"/>

    <item android:drawable="@drawable/xx4" android:duration="500"/>

</animation-list>

將上述的Drawable作為View的背景并通過Drawable來播放動畫.

AnimationDrawable background = (AnimationDrawable) iv_main.getBackground();background.start();

View動畫的特殊使用場景

前面介紹的View動畫都是作用在某一個View對象上的. 還可以針對ViewGroup控制其子元素. 或者針對Activity切換的動畫.

LayoutAnimation

LayoutAnimation作用于ViewGroup上的. 為ViewGroup指定一個動畫, 這樣當它的子元素出場時都會具有這種動畫效果. 常用的使用場景是在ListView和GridView. 使用很簡單步驟如下.

  1. res/anim/文件夾下創(chuàng)建xml文件.
<?xml version="1.0" encoding="utf-8"?>

<layoutAnimation xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"

    android:delay="0.5"

    android:animationOrder="random"

    android:animation="@anim/layout">

</layoutAnimation>

delay: 子元素開始動畫的延遲時間, 傳入值是浮點值. 1為100%. 例如如果是0.5 入場動畫周期為300ms(下面關聯(lián)動畫的duration時間), 那么每個子元素都需要延遲150ms才能播放入場動畫. 而且這個時間會根據(jù)item的遞增而增加. 比方說第一個為延遲150ms, 第二個就是300ms依次類推.

animationOrder: 子元素動畫的順序, 有三種選擇normal,reverse,random. reverse表示排在后面的元素先執(zhí)行入場動畫. random隨機子元素執(zhí)行動畫.

animation: 為子元素指定具體的入場動畫. 里面放的就是針對View的animation動畫的xml

layoutAnimation聲明完成之后, 在要作用的ViewGroup標簽中增加android:layoutAnimation:"@anim/xxx"進行關聯(lián)即可. 同樣也可以通過代碼創(chuàng)建LayoutAnimation類來實現(xiàn).

//獲得子元素需要執(zhí)行的View動畫

Animation animation = AnimationUtils.loadAnimation(this, R.anim.layout);

//創(chuàng)建一個LayoutAnimation動畫對象

LayoutAnimationController controller = new LayoutAnimationController(animation);

controller.setDelay(0.5f);

controller.setOrder(LayoutAnimationController.ORDER_RANDOM);

//對ViewGrop進行綁定

listView.setLayoutAnimation(controller);

Activity的切換效果

Activity默認是有一種切換效果的. 如果需要自定義切換效果, 主要用到overridePendingTransition()這個方法, 這個方法必須在startActivity()或者finish()之后調(diào)用才會生效

需要的形參有兩個, 第一個是被打開時候所需的動畫資源id, 第二個是被暫停時,所需的動畫資源id.

屬性動畫

屬性動畫是API新加入的特性, 和View動畫不同, 它對作用對象進行了擴展, 屬性動畫可以對任何對象做動畫. 屬性動畫不再像View動畫那樣只能支持四種簡單的交換 . 屬性動畫中有valueAnimator. ObjectAnimator, AnimatorSet等概念

使用屬性動畫

屬性動畫可以對任何對象的屬性進行動畫而不僅僅是View, 動畫默認時間間隔為300ms, 默認幀率10ms/幀. 可以達到的效果為: 在一段時間間隔內(nèi)完成對象從一個屬性值到另一個屬性值的改變. 屬性動畫是從API11增加的.

如: 改變一個對象的背景色屬性, 典型的改變View的背景色, 下面的動畫可以讓背景顏色的漸變, 動畫會無限循環(huán)而且會有反轉(zhuǎn)效果.

ObjectAnimator colorAnim = ObjectAnimator.ofInt(activity_main, "backgroundColor", 0xffffa000, 0xffffa0ff);

        colorAnim.setDuration(5000);

        colorAnim.setEvaluator(new ArgbEvaluator());

        colorAnim.setRepeatCount(ValueAnimator.INFINITE);

        colorAnim.setRepeatMode(ValueAnimator.REVERSE);

        colorAnim.start();

動畫集合,5秒內(nèi)對View旋轉(zhuǎn)平移縮放透明

AnimatorSet animatorSet = new AnimatorSet();

        animatorSet.playTogether(

                ObjectAnimator.ofFloat(iv_main, "rotationX", 0,360),

                ObjectAnimator.ofFloat(iv_main, "rotationY", 0,360),

                ObjectAnimator.ofFloat(iv_main, "rotation", 0,360),

                ObjectAnimator.ofFloat(iv_main, "translationX", 0,200),

                ObjectAnimator.ofFloat(iv_main, "translationY", 0,200),

                ObjectAnimator.ofFloat(iv_main, "scaleX", 1,1.5f),

                ObjectAnimator.ofFloat(iv_main, "scaleY", 1,1.5f),

                ObjectAnimator.ofFloat(iv_main, "alpha", 1, 0.25f, 1)

        );

        animatorSet.setDuration(5*1000).start();

也可以使用xml的形式形式來聲明

理解插值器和估值器

TimeInterpolator時間插值器, 作用是根據(jù)時間流逝的百分比來計算當前屬性值改變的百分比. 系統(tǒng)預置的有

  • LinearInterpolator(線性插值器:勻速動畫)
  • AccelerateDecelerateInterpolator(加速減速插值器:動畫兩頭慢中間快)
  • DecelerateInterpolator(減速插值器:動畫越來越慢)

TypeEvaluator 類型估值算法, 也叫估值器. 作用是根據(jù)當前屬性改變的百分比來計算改變后的屬性值. 系統(tǒng)預置的估值器有

  • IntEvaluator 整形估值器
  • FloatEvaluator 浮點型估值器
  • ArgbEvaluator Color屬性估值器

屬性動畫中的插值器和估值器都很重要, 他們是實現(xiàn)非勻速動畫的重要手段

屬性動畫要求對象的該屬性有set``get方法. 插值器和估值器算法除了系統(tǒng)提供的外. 也可以自定義. 實現(xiàn)方式也很簡單, 因為插值器和估值算法都是一個接口, 且內(nèi)部都只有一個方法, 我們只要派生一個類實現(xiàn)接口接可以. 具體就是: 自定義插值器需要實現(xiàn)Interpolator或者TimeInterpolator. 自定義估值算法需要實現(xiàn)TypeEvaluator

屬性動畫的監(jiān)聽器

屬性動畫提供了監(jiān)聽器用于監(jiān)聽動畫的播放過程 主要有兩個接口AnimatorUpdateListenerAnimatorListener接口.

  • AnimatorListener 通過接口的定義可以看出, 監(jiān)聽了動畫的開始,結束,取消,以及重復播放. 系統(tǒng)為了方便開發(fā)提供了AnimatorListenerAdapter類. 他是AnimatorListener的適配器. 這樣就不需要非得實現(xiàn)四個抽象方法而是按照我們的需要選擇復寫.
  • AnimatorUpdateListener 比較特殊, 他會監(jiān)聽整個動畫過程, 動畫是由許多幀組成的. 每播放一幀onAnimationUpdate就會被調(diào)用一次

對任意屬性做動畫

問題: 如果需要把一個button控件的寬增加200px. 應該怎么做?

View動畫只是支持四種基本的屬性操作, 而Scale只是縮放. 并且還會對內(nèi)容進行拉伸并且伴隨著y軸的增加. 所以屬性動畫在這里就可以派上用場. 但是如果直接對width屬性進行修改那么不會有效果. 分析一下:

屬性動畫的原理: 屬性動畫要求動畫作用的對象提供該屬性的get和set方法, 屬性動畫根據(jù)外界傳遞的該屬性值的初始值和最終值, 以動畫的效果多次調(diào)用set每次set的值也是不同. 最終達到終點值.

所以要讓動畫生效應該滿足兩個條件:

  1. 必須提供setXXX()方法, 如果動畫沒有傳遞初始值還要提供getXXX()方法. 這樣系統(tǒng)在需要初始屬性的時候在取值時不會因為沒有getXXX()而發(fā)生Crash.
  2. set修改的值必須能改通過某種形式反映出來, 比如會帶來UI的改變. (如果不滿足這條,動畫無效果但不會Crash)

Button本身具備setWidth()為什么會無效果. 這是因為雖然Button提供了方法, 但是這個setWidth()方法并不是改變視圖大小的, 他是TextView新添加的方法, View卻沒有這樣的方法. 而setWidth()方法的內(nèi)部,作用不是設置View的大小, 而是設置TextView的最大寬度和最小寬度, 這個和TextView的寬是兩個東西. 這樣說控件的寬度對應xml中的layout_width, 而setWidth()對應的就是xml中的width屬性. 所以綜合上述原因, 滿足條件一而不滿足條件二.

官網(wǎng)文檔中給出了三種解決方案:

  1. 給你的對象加上get和set方法, 如果你有權限的話.

  2. 用一個類來包裝原始對象, 間接為其提供get和set方法.

  3. 采用valueAnimator, 監(jiān)聽動畫過程,自己實現(xiàn)屬性的改變.

  4. 雖然簡單但是沒有權限去SDK內(nèi)部實現(xiàn)去

  5. 可以創(chuàng)建一個內(nèi)部包裝類創(chuàng)建set(),get()方法對View的LayoutParams.width進行修改.

  6. 采用ValueAnimator, 監(jiān)聽動畫過程, 自己實現(xiàn)屬性改變. ValueAnimator本身不作用于任何對象. 但是他可以對一個值做動畫. 通過對每個值的分配并會回調(diào)函數(shù)返回此值, 可以手動進行實現(xiàn).

屬性動畫的工作原理

前面說過, 說屬性畫要求作用的對象提供該屬性方法set方法, 屬性動畫根據(jù)傳遞的該屬性的初始值和最終值, 以動畫的效果多次去調(diào)用set方法. 每次set方法時候傳遞的值都是不一樣的. 也就是隨著時間的推移所傳遞的值會越來越接近終點值.

源碼分析: 針對ObjectAnimator的start()為入口

 @Override

public void start() {

   // See if any of the current active/pending animators need to be canceled

   AnimationHandler handler = sAnimationHandler.get();

   if (handler != null) {

       int numAnims = handler.mAnimations.size();

       for (int i = numAnims - 1; i >= 0; i--) {

           if (handler.mAnimations.get(i) instanceof ObjectAnimator) {

               ObjectAnimator anim = (ObjectAnimator) handler.mAnimations.get(i);

               if (anim.mAutoCancel && hasSameTargetAndProperties(anim)) {

                   anim.cancel();

               }

           }

       }

       numAnims = handler.mPendingAnimations.size();

       for (int i = numAnims - 1; i >= 0; i--) {

           if (handler.mPendingAnimations.get(i) instanceof ObjectAnimator) {

               ObjectAnimator anim = (ObjectAnimator) handler.mPendingAnimations.get(i);

               if (anim.mAutoCancel && hasSameTargetAndProperties(anim)) {

                   anim.cancel();

               }

           }

       }

       numAnims = handler.mDelayedAnims.size();

       for (int i = numAnims - 1; i >= 0; i--) {

           if (handler.mDelayedAnims.get(i) instanceof ObjectAnimator) {

               ObjectAnimator anim = (ObjectAnimator) handler.mDelayedAnims.get(i);

               if (anim.mAutoCancel && hasSameTargetAndProperties(anim)) {

                   anim.cancel();

               }

           }

       }

   }

   if (DBG) {

       Log.d(LOG_TAG, "Anim target, duration: " + getTarget() + ", " + getDuration());

       for (int i = 0; i < mValues.length; ++i) {

           PropertyValuesHolder pvh = mValues[i];

           Log.d(LOG_TAG, "   Values[" + i + "]: " +

               pvh.getPropertyName() + ", " + pvh.mKeyframes.getValue(0) + ", " +

               pvh.mKeyframes.getValue(1));

       }

   }

   super.start();

}

這段代碼主要就是取消和當前動畫相同的動畫. 最開始判斷了當前動畫,等待動畫,延遲動畫是否有一致的. 如果有那么就給取消. 最后調(diào)用了父類方法. 因為ObjectAnimator繼承了ValueAnimator,所以繼續(xù)看一下父類的start()

private void start(boolean playBackwards) {

   if (Looper.myLooper() == null) {

       throw new AndroidRuntimeException("Animators may only be run on Looper threads");

   }

   mReversing = playBackwards;

   mPlayingBackwards = playBackwards;

   int prevPlayingState = mPlayingState;

   mPlayingState = STOPPED;

   mStarted = true;

   mStartedDelay = false;

   mPaused = false;

   updateScaledDuration(); // in case the scale factor has changed since creation time

   AnimationHandler animationHandler = getOrCreateAnimationHandler();

   animationHandler.mPendingAnimations.add(this);

   if (mStartDelay == 0) {

       // This sets the initial value of the animation, prior to actually starting it running

       if (prevPlayingState != SEEKED) {

           setCurrentPlayTime(0);

       }

       mPlayingState = STOPPED;

       mRunning = true;

       notifyStartListeners();

   }

   animationHandler.start();

}

屬性動畫需要運行在有Looper的線程中, 最終會調(diào)用AnimationHandler.start()方法. AnimationHandler并不是Handler, 他是一個Runnable. 后面會調(diào)到JNI層, 然后JNI層還會調(diào)回, 然后run方法會被調(diào)用, 這個Runable涉及和底層的交互. 略過. 看重點.

ValueAnimator的doAnimationFrame()方法, 內(nèi)部最后調(diào)用了animationFrame()方法,而animationFrame()內(nèi)部調(diào)用了animateValue()方法

void animateValue(float fraction) {

   fraction = mInterpolator.getInterpolation(fraction);

   mCurrentFraction = fraction;

   int numValues = mValues.length;

   for (int i = 0; i < numValues; ++i) {

       mValues[i].calculateValue(fraction);

   }

   if (mUpdateListeners != null) {

       int numListeners = mUpdateListeners.size();

       for (int i = 0; i < numListeners; ++i) {

           mUpdateListeners.get(i).onAnimationUpdate(this);

       }

   }

}

看到了calculateValue()方法, 這個就是計算每幀動畫所對應的屬性的值, 然后看一下set,get方法. 比如之前說的如果沒有初始值, 則調(diào)用get方法等.. 查看PropertyValuesHolder類的setupValue()

private void setupValue(Object target, Keyframe kf) {

   if (mProperty != null) {

       Object value = convertBack(mProperty.get(target));

       kf.setValue(value);

   }

  if (mGetter == null) {

      Class targetClass = target.getClass();

      setupGetter(targetClass);

      if (mGetter == null) {

          // Already logged the error - just return to avoid NPE

          return;

      }

  }

  Object value = convertBack(mGetter.invoke(target));

  kf.setValue(value);

當動畫的下一幀到來的時, setAnimatedValue()方法會將新的屬性值給對象, 調(diào)用其set()方法.同樣set也是反射調(diào)用

void setAnimatedValue(Object target) {

   if (mProperty != null) {

       mProperty.set(target, getAnimatedValue());

   }

   if (mSetter != null) {

      mTmpValueArray[0] = getAnimatedValue();

      mSetter.invoke(target, mTmpValueArray);

   }

}

使用動畫的注意事項

  1. OOM問題: 在幀動畫時候容易發(fā)生
  2. 內(nèi)存泄漏: 如果有無限循環(huán)的屬性動畫, 在界面退出的時候一定要停止動畫 ,否則activity會無法釋放. 而View動畫并不存在此問題.
  3. 兼容性問題: 主要是3.0以下系統(tǒng)
  4. View動畫問題: 因為是對原始View做的影像效果. 并未真正改變View. 所以在動畫完成之后.無法GONE掉. 這個時候調(diào)用view.clearAnimation()清除View效果即可
  5. 不要使用px
  6. 動畫交互. 系統(tǒng)3.0之前無論是屬性動畫還是View動畫新的位置都無法觸發(fā)單擊事件.需要注意
  7. 硬件加速的使用

參看文章

《Android 開發(fā)藝術探索》書集
《Android 開發(fā)藝術探索》 07-Andriod動畫深入分析

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容