android動(dòng)畫及用法

android動(dòng)畫及用法

android中三種動(dòng)畫:view animation, drawable animation, property animation(3.0以后引入).
官方鏈接:http://developer.android.com/guide/topics/graphics/overview.html

1.view animation/tweened animation 補(bǔ)間動(dòng)畫

淡入淡出、縮放、平移、旋轉(zhuǎn)四種
給出兩個(gè)關(guān)鍵幀,通過一些算法將給定屬性值在給定的時(shí)間內(nèi)在兩個(gè)關(guān)鍵幀間漸變。
缺點(diǎn):

  • 只能作用于view對(duì)象
  • 只支持alpha,scale,translate,rotate,不支持背景顏色改變
  • 只是改變了View的顯示效果而已,而不會(huì)真正去改變View的屬性

現(xiàn)在屏幕的左上角有一個(gè)按鈕,然后我們通過補(bǔ)間動(dòng)畫將它移動(dòng)到了屏幕的右下角,現(xiàn)在你可以去嘗試點(diǎn)擊一下這個(gè)按鈕,點(diǎn)擊事件是絕對(duì)不會(huì)觸發(fā)的,因?yàn)閷?shí)際上這個(gè)按鈕還是停留在屏幕的左上角,只不過補(bǔ)間動(dòng)畫將這個(gè)按鈕繪制到了屏幕的右下角而已。

可以通過設(shè)置interpolator屬性改變動(dòng)畫漸變的方式,如AccelerateInterpolator,開始時(shí)慢,然后逐漸加快。默認(rèn)為AccelerateDecelerateInterpolator。
xml中放在res/anim目錄下

2.drawable Animation/frame Animation 幀動(dòng)畫

逐幀動(dòng)畫的工作原理很簡(jiǎn)單,其實(shí)就是將一個(gè)完整的動(dòng)畫拆分成一張張單獨(dú)的圖片,然后再將它們連貫起來進(jìn)行播放,類似于動(dòng)畫片的工作原理。

3.property animation

真正改變view的left/top值以及width/height等。

ValueAnimator

ValueAnimator表示一個(gè)動(dòng)畫,包含動(dòng)畫的開始值,結(jié)束值,持續(xù)時(shí)間等屬性。
ValueAnimator封裝了一個(gè)TimeInterpolator,TimeInterpolator定義了屬性值在開始值與結(jié)束值之間的插值方法。
ValueAnimator還封裝了一個(gè)TypeEvaluator,根據(jù)開始、結(jié)束值與TimeInterpolator計(jì)算得到的值計(jì)算出屬性值。
ValueAnimator根據(jù)動(dòng)畫已進(jìn)行的時(shí)間跟動(dòng)畫總時(shí)間(duration)的比計(jì)算出一個(gè)時(shí)間因子(0~1),然后根據(jù)TimeInterpolator計(jì)算出另一個(gè)因子,最后TypeAnimator通過這個(gè)因子計(jì)算出屬性值

//幾個(gè)float值平滑過渡
ValueAnimator anim = ValueAnimator.ofFloat(0f, 5f, 3f, 10f);
anim.setDuration(300);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float currentValue = (Float) animation.getAnimatedValue();
        Log.d("TAG", "cuurent value is " + currentValue);
    }
});
anim.setStartDelay(1000);
anim.setTarget(null);
anim.setRepeatCount(5);
//anim.setInterpolator(value);
//anim.setEvaluator(value);
//anim.setFrameDelay(frameDelay);
anim.start();

ObjectAnimator extends ValueAnimator

ValueAnimator只不過是對(duì)值進(jìn)行了一個(gè)平滑的動(dòng)畫過渡,但我們實(shí)際使用到這種功能的場(chǎng)景好像并不多

float curTranslationX = textview.getTranslationX();
ObjectAnimator oa = ObjectAnimator.ofFloat(image1, "translationX", curTranslationX, -40, curTranslationX);

//ObjectAnimator animator = ObjectAnimator.ofFloat(textview, "alpha", 1f, 0f, 1f);  
oa.setDuration(1000);
oa.addListener(new AnimatorListener() {
    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationRepeat(Animator animation) {}

    @Override
    public void onAnimationEnd(Animator animation) {}

    @Override
    public void onAnimationCancel(Animator animation) {}
});
oa.start();

動(dòng)畫回調(diào)太多了,不想監(jiān)聽那么多事件,使用AnimatorListenerAdapter

oa.addListener(new AnimatorListenerAdapter() {
    public void onAnimationRepeat(Animator animation) {
    }
});

組合動(dòng)畫

實(shí)現(xiàn)組合動(dòng)畫功能主要需要借助AnimatorSet這個(gè)類,這個(gè)類提供了一個(gè)play()方法,如果我們向這個(gè)方法中傳入一個(gè)Animator對(duì)象(ValueAnimator或ObjectAnimator)將會(huì)返回一個(gè)AnimatorSet.Builder的實(shí)例,AnimatorSet.Builder中包括以下四個(gè)方法:

  • after(Animator anim) 將現(xiàn)有動(dòng)畫插入到傳入的動(dòng)畫之后執(zhí)行
  • after(long delay) 將現(xiàn)有動(dòng)畫延遲指定毫秒后執(zhí)行
  • before(Animator anim) 將現(xiàn)有動(dòng)畫插入到傳入的動(dòng)畫之前執(zhí)行
  • with(Animator anim) 將現(xiàn)有動(dòng)畫和傳入的動(dòng)畫同時(shí)執(zhí)行
//image3先從屏幕外移動(dòng)進(jìn)屏幕,然后開始旋轉(zhuǎn)360度,旋轉(zhuǎn)的同時(shí)進(jìn)行淡入淡出操作
ObjectAnimator moveIn = ObjectAnimator.ofFloat(image3, "translationX", -500f, 0f);  
ObjectAnimator rotate = ObjectAnimator.ofFloat(image3, "rotation", 0f, 360f);  
ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(image3, "alpha", 1f, 0f, 1f);  
AnimatorSet animSet = new AnimatorSet();  
animSet.play(rotate).with(fadeInOut).after(moveIn);  
animSet.setDuration(5000);  
animSet.start(); 

使用XML寫動(dòng)畫

使用xml寫動(dòng)畫沒有代碼快,但是可以重用性好。
目錄:res/animator文件夾
共三種標(biāo)簽:

  • <animator> 對(duì)應(yīng)代碼中的ValueAnimator
  • <objectAnimator> 對(duì)應(yīng)代碼中的ObjectAnimator
  • <set> 對(duì)應(yīng)代碼中的AnimatorSet

從0到100平滑過渡的動(dòng)畫:

<animator xmlns:android="http://schemas.android.com/apk/res/android"  
    android:valueFrom="0"  
    android:valueTo="100"  
    android:valueType="intType"/> 

視圖的alpha屬性從1變成0:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"  
    android:valueFrom="1"  
    android:valueTo="0"  
    android:valueType="floatType"  
    android:propertyName="alpha"/> 

將一個(gè)視圖先從屏幕外移動(dòng)進(jìn)屏幕,然后開始旋轉(zhuǎn)360度,旋轉(zhuǎn)的同時(shí)進(jìn)行淡入淡出操作:

<set xmlns:android="http://schemas.android.com/apk/res/android"  
    android:ordering="sequentially" >  
  
    <objectAnimator  
        android:duration="2000"  
        android:propertyName="translationX"  
        android:valueFrom="-500"  
        android:valueTo="0"  
        android:valueType="floatType" >  
    </objectAnimator>  
  
    <set android:ordering="together" >  
        <objectAnimator  
            android:duration="3000"  
            android:propertyName="rotation"  
            android:valueFrom="0"  
            android:valueTo="360"  
            android:valueType="floatType" >  
        </objectAnimator>  
  
        <set android:ordering="sequentially" >  
            <objectAnimator  
                android:duration="1500"  
                android:propertyName="alpha"  
                android:valueFrom="1"  
                android:valueTo="0"  
                android:valueType="floatType" >  
            </objectAnimator>  
            <objectAnimator  
                android:duration="1500"  
                android:propertyName="alpha"  
                android:valueFrom="0"  
                android:valueTo="1"  
                android:valueType="floatType" >  
            </objectAnimator>  
        </set>  
    </set>  
  
</set>  

ValueAnimator的高級(jí)用法

搞清楚什么是TypeEvaluator:
ValueAnimator.ofFloat()方法就是實(shí)現(xiàn)了初始值與結(jié)束值之間的平滑過度,它內(nèi)置了一個(gè)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);  
    }  
}

自定義一個(gè)View,里面使用ValueAnimator.ofObject來定義動(dòng)畫:

public class MyAnimView extends View {  
      
    public static final float RADIUS = 50f;  
  
    private MyPoint 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 MyPoint(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() {  
        MyPoint startPoint = new MyPoint(RADIUS, RADIUS);
        MyPoint endPoint = new MyPoint(getWidth() - RADIUS, getHeight() - RADIUS);  
        ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);  
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {  
            @Override  
            public void onAnimationUpdate(ValueAnimator animation) {  
                currentPoint = (MyPoint) animation.getAnimatedValue();//PointEvaluator計(jì)算好的
                invalidate();
            }  
        });  
        anim.setDuration(5000);  
        anim.start();  
    }  
  
}

MyPoint:

public class MyPoint {

    private float x;

    private float y;

    public MyPoint(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }

}

PointEvaluator:

public class PointEvaluator implements TypeEvaluator<MyPoint> {

    @Override
    public MyPoint evaluate(float fraction, MyPoint startValue, MyPoint endValue) {
        float x = startValue.getX() + fraction * (endValue.getX() - startValue.getX());
        float y = startValue.getY() + fraction * (endValue.getY() - startValue.getY());
        MyPoint point = new MyPoint(x, y);
        return point;
    }
}

效果:


再增加ObjectAnimator,兩個(gè)動(dòng)畫playwith,先看效果:

MyAnimView增加setColor方法:

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

修改startAnimation,使用AnimatorSet將兩個(gè)動(dòng)畫一起播放:

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

ColorEvaluator.java:

//計(jì)算一個(gè)顏色字符串然后返回
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;  
        }  
        // 計(jì)算初始顏色和結(jié)束顏色之間的差值  
        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);  
        }  
        // 將計(jì)算出的當(dāng)前顏色的值組裝返回  
        String currentColor = "#" + getHexString(mCurrentRed)  
                + getHexString(mCurrentGreen) + getHexString(mCurrentBlue);  
        return currentColor;  
    }  
  
    /** 
     * 根據(jù)fraction值來計(jì)算當(dāng)前的顏色。 
     */  
    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進(jìn)制顏色值轉(zhuǎn)換成16進(jìn)制。 
     */  
    private String getHexString(int value) {  
        String hexString = Integer.toHexString(value);  
        if (hexString.length() == 1) {  
            hexString = "0" + hexString;  
        }  
        return hexString;  
    }  
  
}  

Intorplator:
第一個(gè)動(dòng)畫增加以下:

anim.setInterpolator(new BounceInterpolator());

設(shè)置TimeInterpolator,這個(gè)接口要實(shí)現(xiàn)float getInterpolation(float input);
時(shí)間因子input(0~1):已進(jìn)行的時(shí)間跟動(dòng)畫總時(shí)間的比,0代表開始,1代表結(jié)束

ViewPropertyAnimator

它是3.1系統(tǒng)中增加的一個(gè)功能。是為了方便使用ObjctAnimator來操作View,代碼更加人性化。

參考:
http://developer.android.com/guide/topics/graphics/overview.html
http://www.cnblogs.com/angeldevil/archive/2011/12/02/2271096.html
http://blog.csdn.net/guolin_blog/article/details/43536355

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,786評(píng)論 6 534
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,656評(píng)論 3 419
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,697評(píng)論 0 379
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,098評(píng)論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,855評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,254評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,322評(píng)論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,473評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,014評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,833評(píng)論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,016評(píng)論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,568評(píng)論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,273評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,680評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,946評(píng)論 1 288
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,730評(píng)論 3 393
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,006評(píng)論 2 374

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