Android 屬性動畫(二)

上一篇 Android 屬性動畫(一) 介紹了Property Animator 的基本用法。今天繼續(xù)了解Property Animator 的Evaluator、Interpolator 和 xml 文件定義Animator 的相關(guān)知識和用法。

Evaluator 求值器

直接貼源碼:

public interface TypeEvaluator<T> {    
/**     
    * This function returns the result of linearly interpolating the start and end values, with   
    * <code>fraction</code> representing the proportion between the start and end values. The     
    * calculation is a simple parametric calculation: <code>result = x0 + t * (x1 - x0)</code>,    
    * where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>,     
    * and <code>t</code> is <code>fraction</code>.     
    * 
    * @param fraction   The fraction from the starting to the ending values     
    * @param startValue The start value.     
    * @param endValue   The end value.     
    * @return A linear interpolation between the start and end values, given the     
    *         <code>fraction</code> parameter.     
    */    
public T evaluate(float fraction, T startValue, T endValue);
}

源碼很簡短,就一個方法,默認(rèn)實現(xiàn)就是 根據(jù)fraction 通過 result = x0 + t * (x1 - x0) 公式計算返回一個中間值。
那么 fraction 這個參數(shù)是多少呢?通過ValueAnimator 的setEvaluator() 方法找到源碼:

boolean animationFrame(long currentTime) {    
    boolean done = false;
    switch (mPlayingState) {
    case RUNNING:
    case SEEKED:
        float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f;
        if (mDuration == 0 && mRepeatCount != INFINITE) {
            // Skip to the end 
           mCurrentIteration = mRepeatCount;
            if (!mReversing) {
                mPlayingBackwards = false;
            }
        }
        if (fraction >= 1f) {
            if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE)
            {                
                // Time to repeat
                if (mListeners != null) {
                    int numListeners = mListeners.size();
                    for (int i = 0; i < numListeners; ++i) {
                        mListeners.get(i).onAnimationRepeat(this);
                    }
                }
                if (mRepeatMode == REVERSE) {
                    mPlayingBackwards = !mPlayingBackwards;
                }
                mCurrentIteration += (int) fraction;
                fraction = fraction % 1f;
                mStartTime += mDuration;
                // Note: We do not need to update the value of mStartTimeCommitted here
                // since we just added a duration offset.
            } else {
                done = true;
                fraction = Math.min(fraction, 1.0f);
            }
        }
        if (mPlayingBackwards) {
            fraction = 1f - fraction;
        }
        animateValue(fraction);
        break;
    }
    return done;
}

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);
        }
    }
}

在 ValueAnimator 類中有兩個方法,可以看到在 animationFrame 方法就是 得到一個已完成時間在總時長的比例值(0~1)并賦值給 fraction,在 animateValue 方法中 調(diào)用了 mInterpolator.getInterpolation() (就是 插值器,后面會介紹) 目的就是修正 fraction 。所以我們知道 fraction 是一個0~1 的值。現(xiàn)在看下自定義Evaluator 的代碼:

//定義了一個 PointF 類型的 Evaluator ,實現(xiàn) view 的拋物線變化
//默認(rèn) TypeEvaluator View 在X,Y方向都是勻速的。
//自定義后,View的Y方向是變速的。

ValueAnimator valueAnimator = ValueAnimator.ofObject(new TypeEvaluator<PointF>(){
    @Override    public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
        // y 方向是一個變速        PointF point = new PointF();
        point.x = startValue.x + fraction * (endValue.x - startValue.x) ;
        point.y = (float) (startValue.y + Math.pow(fraction , 2) * (endValue.y - startValue.y));
        return point;
    }},
new PointF(0,0),new PointF(400,1000));
valueAnimator.setDuration(3000);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.start();
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
         @Override    
        public void onAnimationUpdate(ValueAnimator animation)    {
        PointF point = (PointF) animation.getAnimatedValue();
        animView.setX(point.x);
        animView.setY(point.y);
    }});
valueAnimator.start();

Interpolator 插值器

本來想寫下Interpolayor的源碼分析的,但看到一篇 Interpolayor的分析文章后,感覺自己也不會寫的比這個好,所以還是不寫了,借鑒和學(xué)習(xí)這篇文章 李海珍大神的 android動畫(一)Interpolator。膜拜!!!
一下是從 大神文章中摘抄的部分,圖文并茂,講解很詳細(xì),大家學(xué)習(xí)下!

二:簡單插值器分析
** 注意下面的圖,對應(yīng)你腦海中的插值的大小應(yīng)該是斜率。**

package android.view.animation;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
/**
 *
 * 一個開始很慢然后不斷加速的插值器。 
 * <hr/>
 * An interpolator where the rate of change starts out slowly and
 * and then accelerates.
 *
 */
public class AccelerateInterpolator implements Interpolator {
     private final float mFactor; private final double mDoubleFactor;
     public AccelerateInterpolator() {
        mFactor = 1.0f;
        mDoubleFactor = 2.0;
     }
     /**     
       * Constructor
       *
       * @param factor
       * 動畫的快慢度。將factor設(shè)置為1.0f會產(chǎn)生一條y=x^2的拋物線。增加factor到1.0f之后為加大這種漸入效果(也就是說它開頭更加慢,結(jié)尾更加快)
       * <br/>Degree to which the animation should be eased. Seting
       * factor to 1.0f produces a y=x^2 parabola(拋物線). Increasing factor above
       * 1.0f exaggerates the ease-in effect (i.e., it starts even   * slower and ends evens faster)
      */
      public AccelerateInterpolator(float factor) {
        mFactor = factor;
        mDoubleFactor = 2 * mFactor;
      } 
      public AccelerateInterpolator(Context context, AttributeSet attrs) {
        TypedArray a =context.obtainStyledAttributes(attrs,com.android.internal.R.styleable.AccelerateInterpolator);
        mFactor = a.getFloat(com.android.internal.R.styleable.AccelerateInterpolator_factor, 1.0f);
        mDoubleFactor = 2 * mFactor;
        a.recycle();
      }
      @Override 
      public float getInterpolation(float input) {
         if (mFactor == 1.0f) {
             return input * input;  
          } else {
              return (float)Math.pow(input, mDoubleFactor);
          } 
      }
}

加速的快慢度由參數(shù)fractor決定。
當(dāng)fractor值為1.0f時,動畫加速軌跡相當(dāng)于一條y=x^2的拋物線。如下圖:


當(dāng)fractor不為1時,軌跡曲線是y=x^(2*fractor)(0<x<=1)的曲線。
示例:當(dāng)fractor為4時,插值器的加速軌跡曲線如下圖:

如果你在使用AccelerateInterpolator時,想要那種一開始很慢,然后突然就很快的加速的動畫效果的話。
就將fractor設(shè)置大點。
你可以到這里調(diào)試下你想要的拋物線效果:http://www.wolframalpha.com/input/?i=x%5E%282*3%29%280%3Cx%3C%3D1%29

Android提供的一個不同factor的加速插值器:
(1)accelerate_cubic, factor為1.5

xml 文件定義Animator

大家應(yīng)該都在xml 文件定義過 幀動畫 和 補間動畫。今天,我們就在xml中定義屬性動畫,來看看有什么區(qū)別。
先在 res 文件下創(chuàng)建 anmator 文件夾,在創(chuàng)建 res/animator/animator_set.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"    
    android:ordering="together">
    <objectAnimator
        android:duration="1000"
        android:propertyName="scaleX"
        android:valueFrom="1"
        android:valueTo="0.5">
    </objectAnimator>
    <objectAnimator
        android:duration="1000"
        android:propertyName="scaleY"
        android:valueFrom="1"
        android:valueTo="0.5">
    </objectAnimator>
</set>

這個文件是實現(xiàn) 同時縮放XY軸的動畫集合,我們可以看到 set 標(biāo)簽 動畫集合有個
android:ordering 屬性,android:ordering 有兩個值 :together(同時執(zhí)行),sequentially (順序執(zhí)行)。接下來在代碼中加載動畫:

// 加載動畫
Animator anim = AnimatorInflater.loadAnimator(this, R.animator.animator_set);
//設(shè)置 縮放的中心點
animView.setPivotX(0);
animView.setPivotY(0);
//顯示的調(diào)用invalidate
animView.invalidate();
anim.setTarget(animView);
anim.start();

如上,將 animView 設(shè)為target 就可以了。 當(dāng)然,縮放 和旋轉(zhuǎn)都可以設(shè)置中心點的,我們將縮放的中心點設(shè)置在了 (0,0),默認(rèn)都是在對象中心點。如果,只想實現(xiàn)單個動畫,可以在xml 中去掉 set標(biāo)簽。

下面是總結(jié)
今天介紹了 Property Animator 的 Evaluator 、Interpolator 和 xml 定義,我們可以跟愉快的實現(xiàn)酷炫的動畫啦。當(dāng)然,在看了Interpolator 的文章后,還是佩服的五體投地的,我們要努力,像大神看齊!
接下來,我會總結(jié)下 ** 布局動畫(Layout Animations)** ,然后就是 屬性動畫實戰(zhàn)啦,233333。fighting!!!

源碼,源碼中還有我之前寫的防直播打賞禮物動畫效果。歡迎大家指教!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 1 背景 不能只分析源碼呀,分析的同時也要整理歸納基礎(chǔ)知識,剛好有人微博私信讓全面說說Android的動畫,所以今...
    未聞椛洺閱讀 2,755評論 0 10
  • Animation Animation類是所有動畫(scale、alpha、translate、rotate)的基...
    四月一號閱讀 1,936評論 0 10
  • 時常在想究竟是為什么讓我進(jìn)入了汽車行業(yè)? 這是我畢業(yè)后第一份正規(guī)職業(yè),因為身體的原因,所以我選擇的是人事和行政。可...
    小元子美眉閱讀 422評論 0 1
  • 臨近寒冬,白晝愈來愈短,晚上下班,出地鐵站,臨近八點,外面的世界除了寒意侵人,便是黑夜,深深的黑;燈火通明的地鐵站...
    咖啡與薔薇閱讀 269評論 0 0
  • 很久以前,知道世上有個你。 讓河流接住倒影,讓鮮花及時怒放,讓年華傾其所有,三十六歲的你還是畫一般的模樣。 人前你...
    青灰搖閱讀 544評論 4 4