Android屬性動畫-ValueAnimator和ObjectAnimator的高級用法


ValueAnimator的高級用法

在上篇文章中介紹補間動畫缺點的時候有提到過,補間動畫是只能對View對象進行動畫操作的。而屬性動畫就不再受這個限制,它可以對任意對象進行動畫操作。那么大家應該還記得在上篇文章當中我舉的一個例子,比如說我們有一個自定義的View,在這個View當中有一個Point對象用於管理坐標,然后在onDraw()方法當中就是根據這個Point對象的坐標值來進行繪制的。也就是說,如果我們可以對Point對象進行動畫操作,那么整個自定義View的動畫效果就有了。OK,下面我們就來學習一下如何實現這樣的效果。

在開始動手之前,我們還需要掌握另外一個知識點,就是TypeEvaluator的用法。可能在大多數情況下我們使用屬性動畫的時候都不會用到TypeEvaluator,但是大家還是應該了解一下它的用法,以防止當我們遇到一些解決不掉的問題時能夠想起來還有這樣的一種解決方案。

那么TypeEvaluator的作用到底是什么呢?簡單來說,就是告訴動畫系統如何從初始值過度到結束值。我們在上一篇文章中學到的ValueAnimator.ofFloat()方法就是實現了初始值與結束值之間的平滑過度,那么這個平滑過度是怎么做到的呢?其實就是系統內置了一個FloatEvaluator,它通過計算告知動畫系統如何從初始值過度到結束值,我們來看一下FloatEvaluator的代碼實現:

public class FloatEvaluator implements TypeEvaluator {  
    public Object evaluate(float fraction, Object startValue, Object endValue) {  
        float startFloat = ((Number) startValue).floatValue();  
        return startFloat + fraction * (((Number) endValue).floatValue() - startFloat);  
    }  
}  

 可以看到,FloatEvaluator實現了TypeEvaluator接口,然后重寫evaluate()方法。evaluate()方法當中傳入了三個參數,第一個參數fraction非常重要,這個參數用於表示動畫的完成度的,我們應該根據它來計算當前動畫的值應該是多少,第二第三個參數分別表示動畫的初始值和結束值。那么上述代碼的邏輯就比較清晰了,用結束值減去初始值,算出它們之間的差值,然后乘以fraction這個系數,再加上初始值,那么就得到當前動畫的值了。

好的,那FloatEvaluator是系統內置好的功能,並不需要我們自己去編寫,但介紹它的實現方法是要為我們后面的功能鋪路的。前面我們使用過了ValueAnimator的ofFloat()和ofInt()方法,分別用於對浮點型和整型的數據進行動畫操作的,但實際上ValueAnimator中還有一個ofObject()方法,是用於對任意對象進行動畫操作的。但是相比於浮點型或整型數據,對象的動畫操作明顯要更復雜一些,因為系統將完全無法知道如何從初始對象過度到結束對象,因此這個時候我們就需要實現一個自己的TypeEvaluator來告知系統如何進行過度。

下面來先定義一個Point類,如下所示:

public class Point {  
  
    private float x;  
  
    private float y;  
  
    public Point(float x, float y) {  
        this.x = x;  
        this.y = y;  
    }  
  
    public float getX() {  
        return x;  
    }  
  
    public float getY() {  
        return y;  
    }  
  
}  

 Point類非常簡單,只有x和y兩個變量用於記錄坐標的位置,並提供了構造方法來設置坐標,以及get方法來獲取坐標。接下來定義PointEvaluator,如下所示:

public class PointEvaluator implements TypeEvaluator{  
  
    @Override  
    public Object evaluate(float fraction, Object startValue, Object endValue) {  
        Point startPoint = (Point) startValue;  
        Point endPoint = (Point) endValue;  
        float x = startPoint.getX() + fraction * (endPoint.getX() - startPoint.getX());  
        float y = startPoint.getY() + fraction * (endPoint.getY() - startPoint.getY());  
        Point point = new Point(x, y);  
        return point;  
    }  
  
}  

 可以看到,PointEvaluator同樣實現了TypeEvaluator接口並重寫了evaluate()方法。其實evaluate()方法中的邏輯還是非常簡單的,先是將startValue和endValue強轉成Point對象,然后同樣根據fraction來計算當前動畫的x和y的值,最后組裝到一個新的Point對象當中並返回。

這樣我們就將PointEvaluator編寫完成了,接下來我們就可以非常輕松地對Point對象進行動畫操作了,比如說我們有兩個Point對象,現在需要將Point1通過動畫平滑過度到Point2,就可以這樣寫:

Point point1 = new Point(0, 0);  
Point point2 = new Point(300, 300);  
ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), point1, point2);  
anim.setDuration(5000);  
anim.start(); 

 代碼很簡單,這里我們先是new出了兩個Point對象,並在構造函數中分別設置了它們的坐標點。然后調用ValueAnimator的ofObject()方法來構建ValueAnimator的實例,這里需要注意的是,ofObject()方法要求多傳入一個TypeEvaluator參數,這里我們只需要傳入剛才定義好的PointEvaluator的實例就可以了。

好的,這就是自定義TypeEvaluator的全部用法,掌握了這些知識之后,我們就可以來嘗試一下如何通過對Point對象進行動畫操作,從而實現整個自定義View的動畫效果。

新建一個MyAnimView繼承自View,代碼如下所示:

public class MyAnimView extends View {  
  
    public static final float RADIUS = 50f;  
  
    private Point currentPoint;  
  
    private Paint mPaint;  
  
    public MyAnimView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);  
        mPaint.setColor(Color.BLUE);  
    }  
  
    @Override  
    protected void onDraw(Canvas canvas) {  
        if (currentPoint == null) {  
            currentPoint = new Point(RADIUS, RADIUS);  
            drawCircle(canvas);  
            startAnimation();  
        } else {  
            drawCircle(canvas);  
        }  
    }  
  
    private void drawCircle(Canvas canvas) {  
        float x = currentPoint.getX();  
        float y = currentPoint.getY();  
        canvas.drawCircle(x, y, RADIUS, mPaint);  
    }  
  
    private void startAnimation() {  
        Point startPoint = new Point(RADIUS, RADIUS);  
        Point endPoint = new Point(getWidth() - RADIUS, getHeight() - RADIUS);  
        ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);  
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {  
            @Override  
            public void onAnimationUpdate(ValueAnimator animation) {  
                currentPoint = (Point) animation.getAnimatedValue();  
                invalidate();  
            }  
        });  
        anim.setDuration(5000);  
        anim.start();  
    }  
  
}  

 基本上還是很簡單的,總共也沒幾行代碼。首先在自定義View的構造方法當中初始化了一個Paint對象作為畫筆,並將畫筆顏色設置為藍色,接着在onDraw()方法當中進行繪制。這里我們繪制的邏輯是由currentPoint這個對象控制的,如果currentPoint對象不等於空,那么就調用drawCircle()方法在currentPoint的坐標位置畫出一個半徑為50的圓,如果currentPoint對象是空,那么就調用startAnimation()方法來啟動動畫。

那么我們來觀察一下startAnimation()方法中的代碼,其實大家應該很熟悉了,就是對Point對象進行了一個動畫操作而已。這里我們定義了一個startPoint和一個endPoint,坐標分別是View的左上角和右下角,並將動畫的時長設為5秒。然后有一點需要大家注意的,就是我們通過監聽器對動畫的過程進行了監聽,每當Point值有改變的時候都會回調onAnimationUpdate()方法。在這個方法當中,我們對currentPoint對象進行了重新賦值,並調用了invalidate()方法,這樣的話onDraw()方法就會重新調用,並且由於currentPoint對象的坐標已經改變了,那么繪制的位置也會改變,於是一個平移的動畫效果也就實現了。

下面我們只需要在布局文件當中引入這個自定義控件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    >  
  
    <com.example.tony.myapplication.MyAnimView  
        android:layout_width="match_parent"  
        android:layout_height="match_parent" />  
  
</RelativeLayout>  

 

最后運行一下程序,效果如下圖所示:

OK!這樣我們就成功實現了通過對對象進行值操作來實現動畫效果的功能,這就是ValueAnimator的高級用法。

ObjectAnimator的高級用法

ObjectAnimator的基本用法和工作原理在上一篇文章當中都已經講解過了,相信大家都已經掌握。那么大家應該都還記得,我們在吐槽補間動畫的時候有提到過,補間動畫是只能實現移動、縮放、旋轉和淡入淡出這四種動畫操作的,功能限定死就是這些,基本上沒有任何擴展性可言。比如我們想要實現對View的顏色進行動態改變,補間動畫是沒有辦法做到的。

但是屬性動畫就不會受這些條條框框的限制,它的擴展性非常強,對於動態改變View的顏色這種功能是完全可是勝任的,那么下面我們就來學習一下如何實現這樣的效果。

大家應該都還記得,ObjectAnimator內部的工作機制是通過尋找特定屬性的get和set方法,然后通過方法不斷地對值進行改變,從而實現動畫效果的。因此我們就需要在MyAnimView中定義一個color屬性,並提供它的get和set方法。這里我們可以將color屬性設置為字符串類型,使用#RRGGBB這種格式來表示顏色值,代碼如下所示:

public class MyAnimView extends View {  
  
    ...  
  
    private String color;  
  
    public String getColor() {  
        return color;  
    }  
  
    public void setColor(String color) {  
        this.color = color;  
        mPaint.setColor(Color.parseColor(color));  
        invalidate();  
    }  
  
    ...  
  
}  

 注意在setColor()方法當中,我們編寫了一個非常簡單的邏輯,就是將畫筆的顏色設置成方法參數傳入的顏色,然后調用了invalidate()方法。這段代碼雖然只有三行,但是卻執行了一個非常核心的功能,就是在改變了畫筆顏色之后立即刷新視圖,然后onDraw()方法就會調用。在onDraw()方法當中會根據當前畫筆的顏色來進行繪制,這樣顏色也就會動態進行改變了。

那么接下來的問題就是怎樣讓setColor()方法得到調用了,毫無疑問,當然是要借助ObjectAnimator類,但是在使用ObjectAnimator之前我們還要完成一個非常重要的工作,就是編寫一個用於告知系統如何進行顏色過度的TypeEvaluator。創建ColorEvaluator並實現TypeEvaluator接口,代碼如下所示:

public class ColorEvaluator implements TypeEvaluator {  
  
    private int mCurrentRed = -1;  
  
    private int mCurrentGreen = -1;  
  
    private int mCurrentBlue = -1;  
  
    @Override  
    public Object evaluate(float fraction, Object startValue, Object endValue) {  
        String startColor = (String) startValue;  
        String endColor = (String) endValue;  
        int startRed = Integer.parseInt(startColor.substring(1, 3), 16);  
        int startGreen = Integer.parseInt(startColor.substring(3, 5), 16);  
        int startBlue = Integer.parseInt(startColor.substring(5, 7), 16);  
        int endRed = Integer.parseInt(endColor.substring(1, 3), 16);  
        int endGreen = Integer.parseInt(endColor.substring(3, 5), 16);  
        int endBlue = Integer.parseInt(endColor.substring(5, 7), 16);  
        // 初始化顏色的值  
        if (mCurrentRed == -1) {  
            mCurrentRed = startRed;  
        }  
        if (mCurrentGreen == -1) {  
            mCurrentGreen = startGreen;  
        }  
        if (mCurrentBlue == -1) {  
            mCurrentBlue = startBlue;  
        }  
        // 計算初始顏色和結束顏色之間的差值  
        int redDiff = Math.abs(startRed - endRed);  
        int greenDiff = Math.abs(startGreen - endGreen);  
        int blueDiff = Math.abs(startBlue - endBlue);  
        int colorDiff = redDiff + greenDiff + blueDiff;  
        if (mCurrentRed != endRed) {  
            mCurrentRed = getCurrentColor(startRed, endRed, colorDiff, 0,  
                    fraction);  
        } else if (mCurrentGreen != endGreen) {  
            mCurrentGreen = getCurrentColor(startGreen, endGreen, colorDiff,  
                    redDiff, fraction);  
        } else if (mCurrentBlue != endBlue) {  
            mCurrentBlue = getCurrentColor(startBlue, endBlue, colorDiff,  
                    redDiff + greenDiff, fraction);  
        }  
        // 將計算出的當前顏色的值組裝返回  
        String currentColor = "#" + getHexString(mCurrentRed)  
                + getHexString(mCurrentGreen) + getHexString(mCurrentBlue);  
        return currentColor;  
    }  
  
    /** 
     * 根據fraction值來計算當前的顏色。 
     */  
    private int getCurrentColor(int startColor, int endColor, int colorDiff,  
            int offset, float fraction) {  
        int currentColor;  
        if (startColor > endColor) {  
            currentColor = (int) (startColor - (fraction * colorDiff - offset));  
            if (currentColor < endColor) {  
                currentColor = endColor;  
            }  
        } else {  
            currentColor = (int) (startColor + (fraction * colorDiff - offset));  
            if (currentColor > endColor) {  
                currentColor = endColor;  
            }  
        }  
        return currentColor;  
    }  
      
    /** 
     * 將10進制顏色值轉換成16進制。 
     */  
    private String getHexString(int value) {  
        String hexString = Integer.toHexString(value);  
        if (hexString.length() == 1) {  
            hexString = "0" + hexString;  
        }  
        return hexString;  
    }  
  
}  

 這大概是我們整個動畫操作當中最復雜的一個類了。沒錯,屬性動畫的高級用法中最有技術含量的也就是如何編寫出一個合適的TypeEvaluator。好在剛才我們已經編寫了一個PointEvaluator,對它的基本工作原理已經有了了解,那么這里我們主要學習一下ColorEvaluator的邏輯流程吧。

首先在evaluate()方法當中獲取到顏色的初始值和結束值,並通過字符串截取的方式將顏色分為RGB三個部分,並將RGB的值轉換成十進制數字,那么每個顏色的取值范圍就是0-255。接下來計算一下初始顏色值到結束顏色值之間的差值,這個差值很重要,決定着顏色變化的快慢,如果初始顏色值和結束顏色值很相近,那么顏色變化就會比較緩慢,而如果顏色值相差很大,比如說從黑到白,那么就要經歷255*3這個幅度的顏色過度,變化就會非常快。

那么控制顏色變化的速度是通過getCurrentColor()這個方法來實現的,這個方法會根據當前的fraction值來計算目前應該過度到什么顏色,並且這里會根據初始和結束的顏色差值來控制變化速度,最終將計算出的顏色進行返回。

最后,由於我們計算出的顏色是十進制數字,這里還需要調用一下getHexString()方法把它們轉換成十六進制字符串,再將RGB顏色拼裝起來之后作為最終的結果返回。

好了,ColorEvaluator寫完之后我們就把最復雜的工作完成了,剩下的就是一些簡單調用的問題了,比如說我們想要實現從藍色到紅色的動畫過度,歷時5秒,就可以這樣寫:

ObjectAnimator anim = ObjectAnimator.ofObject(myAnimView, "color", new ColorEvaluator(),   
    "#0000FF", "#FF0000");  
anim.setDuration(5000);  
anim.start();  

 用法非常簡單易懂,相信不需要我再進行解釋了。

接下來我們需要將上面一段代碼移到MyAnimView類當中,讓它和剛才的Point移動動畫可以結合到一起播放,這就要借助我們在上篇文章當中學到的組合動畫的技術了。修改MyAnimView中的代碼,如下所示:

public class MyAnimView extends View {  
  
    ...  
  
    private void startAnimation() {  
        Point startPoint = new Point(RADIUS, RADIUS);  
        Point endPoint = new Point(getWidth() - RADIUS, getHeight() - RADIUS);  
        ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);  
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {  
            @Override  
            public void onAnimationUpdate(ValueAnimator animation) {  
                currentPoint = (Point) animation.getAnimatedValue();  
                invalidate();  
            }  
        });  
        ObjectAnimator anim2 = ObjectAnimator.ofObject(this, "color", new ColorEvaluator(),   
                "#0000FF", "#FF0000");  
        AnimatorSet animSet = new AnimatorSet();  
        animSet.play(anim).with(anim2);  
        animSet.setDuration(5000);  
        animSet.start();  
    }  
  
}  

 可以看到,我們並沒有改動太多的代碼,重點只是修改了startAnimation()方法中的部分內容。這里先是將顏色過度的代碼邏輯移動到了startAnimation()方法當中,注意由於這段代碼本身就是在MyAnimView當中執行的,因此ObjectAnimator.ofObject()的第一個參數直接傳this就可以了。接着我們又創建了一個AnimatorSet,並把兩個動畫設置成同時播放,動畫時長為五秒,最后啟動動畫。現在重新運行一下代碼,效果如下圖所示:

 

OK,位置動畫和顏色動畫非常融洽的結合到一起了,看上去效果還是相當不錯的,這樣我們就把ObjectAnimator的高級用法也掌握了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM