Animation插值器:解決Android Animation 循環執行的停頓問題

在Android開發中,有時候我們需要一個動畫一直循環執行下去,常見的如laoding菊花一直旋轉,這時候就需要使用Animation的repeat功能,如下:
animation = new RotateAnimation(0f, 360f, lightView.getWidth() / 2, lightView.getHeight() / 2);
animation.setDuration(2500);
animation.setRepeatMode(Animation.RESTART);
animation.setRepeatCount(Animation.INFINITE);
lightView.startAnimation(animation);


爲lightView執行以中心爲圓點的旋轉動畫。

repeatMode設爲RESTART,在動畫執行結束後繼續從頭執行。由於單次動畫是旋轉一週,這樣兩次動畫可以銜接在一起。
repeatCount設爲INFINITE來保證無限循環執行動畫。

在實際的展示效果中,你會發現每次動畫播放完都會停頓一下再去播放下次動畫,動畫無法連貫的執行。
其實並不是動畫間有停頓,而是animation的插值器的效果。
解決方法很簡單,爲Animation設置線性插值器即可:
animation.setInterpolator(new LinearInterpolator());


這樣我們解決了問題,但是爲什麼要這麼做呢?
來看看Animation的構造函數源碼:
public Animation() {
    ensureInterpolator();
}

public Animation(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Animation);
    ...

    ensureInterpolator();
}


可以看到構造函數中都會調用ensureInterpolator函數,這個函數源碼如下:
protected void ensureInterpolator() {
    if (mInterpolator == null) {
        mInterpolator = new AccelerateDecelerateInterpolator();
    }
}

所以,Animation默認會使用AccelerateDecelerateInterpolator這個插值器,這個插值器的作用是動畫播放有個加速減速的過程,類似汽車啓動和剎車的效果,開始播放時會從靜止狀態逐漸加速直到勻速,接近結束時會逐漸減速直至停止。所以當我們未設置其他插值器的時候,由於這個插值器的作用導致動畫效果上無法連貫,有一個停頓的效果。

而線性插值器LinearInterpolator的效果是動畫全程勻速執行,這樣當我們設置了這個插值器動畫就可以連貫起來。

插值器極大的豐富了Animation的效果,我們可以通過系統自帶的或者自定義的插值器來完成很多酷炫的效果,大家有興趣可以找資料看一下。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章