2016 Android 動畫 詳解 乾貨(二)

昨天我使用所學的新的技術完成了一個 轉盤抽獎的小遊戲。這些遊戲的設計和實現以及原碼會逐步的給大家放出來。

今天就來看些高級的用法和使用技巧。
ValueAnimator 屬性動畫,其生成的並不是一個特定的效果,而是一些列可加速減速勻速的數據,以此使我們的動畫看起來更佳平滑美觀。他就不在是簡簡單單的移動了。正因爲屬性動畫產生的是數據這個特性,所以對於屬性動畫來說,他所適應的對象不再僅僅是View了任何使用JAVA實現的頁面,在實現過渡動畫的時候都可以使用屬性動畫進行演示。例如我們希望在onDraw裏面平緩的畫一條線,原來的時候我們是canvas直接畫那就是直接出現一條線,那麼現在我們使用了屬性動畫,我們就可以,讓ValueAnimator對長度進行一個過渡,那麼我們就可以模擬真實在畫板上由一點出發,然後畫出一條線了。話句話說ValueAnimator是可以對點線這些基本元素進行操作的。

在開始動手之前,我們還需要掌握另外一個知識點,就是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>  

最後運行一下程序,效果如下圖所示:
這裏寫圖片描述

這個例子主要是讓我們知道 屬性動畫的真正用法,實在View層對我們的控件進行一個控制。

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 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,並把兩個動畫設置成同時播放,動畫時長爲五秒,最後啓動動畫。現在重新運行一下代碼,效果如下圖所示:

這裏寫圖片描述

最後說一下,對於顏色算法的部分轉換顏色不一定要按照那個寫,也可以按照自己的設計情況進行重寫。這裏只是起到一個非常好的例子告訴大家在什麼地方進行使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章