轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/43536355
大家好,在上一篇文章當中,我們學習了Android屬性動畫的基本用法,當然也是最常用的一些用法,這些用法足以覆蓋我們平時大多情況下的動畫需求了。但是,正如上篇文章當中所說到的,屬性動畫對補間動畫進行了很大幅度的改進,之前補間動畫可以做到的屬性動畫也能做到,補間動畫做不到的現在屬性動畫也可以做到了。因此,今天我們就來學習一下屬性動畫的高級用法,看看如何實現一些補間動畫所無法實現的功能。
閱讀本篇文章需要你對屬性動畫有一定的瞭解,並且掌握屬性動畫的基本用法,如果你還對屬性動畫不夠了解的話,建議先去閱讀 Android屬性動畫完全解析(上),初識屬性動畫的基本用法 。
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是系統內置好的功能,並不需要我們自己去編寫,但介紹它的實現方法是要爲我們後面的功能鋪路的。前面我們使用過了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編寫完成了,接下來我們就可以非常輕鬆地對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();
好的,這就是自定義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();
- }
- }
那麼我們來觀察一下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()方法得到調用了,毫無疑問,當然是要藉助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;
- }
- }
首先在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();
- }
- }
OK,位置動畫和顏色動畫非常融洽的結合到一起了,看上去效果還是相當不錯的,這樣我們就把ObjectAnimator的高級用法也掌握了。
好的,通過本篇文章的學習,我們對屬性動畫已經有了頗爲深刻的認識,那麼本篇文章的內容到此爲止,下篇文章當中將會介紹更多關於屬性動畫的其它技巧,感興趣的朋友請繼續閱讀 Android屬性動畫完全解析(下),Interpolator和ViewPropertyAnimator的用法 。