在MIUI上看到很多顏色漸變動畫,感覺很炫,用ObjectAnimator試了一下能實(shí)現(xiàn)初步效果,一下是源代碼
使用ObjectAnimator實(shí)現(xiàn)顏色漸變動畫
ObjectAnimator animator = ObjectAnimator.ofObject(testLayout, "backgroundColor",new ArgbEvaluator(),0xff40c7b6,0xffff7a59);
animator.setDuration(1000);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.start();
看起來很容易,但是我留意到進(jìn)度條變化的時候背景顏色跟著一起變化,用這個方法只能能實(shí)現(xiàn)從某個顏色變化到某個顏色并不能在中間停頓保留,我上網(wǎng)搜索了下,很多大佬使用的是自定義TypeEvaluator來計(jì)算屬性動畫的屬性值,但是想實(shí)現(xiàn)停留在中的顏色還是停留不了,于是我拿DALAO的代碼進(jìn)行了一部分抽離
public void startValueAnimator(int progress,int mProgress){
if(animator != null && animator.isRunning()){
animator.cancel();
animator = null;
}
int duration = 15 * Math.abs(progress - mProgress);
animator = ObjectAnimator.ofObject(testLayout, "backgroundColor",new ArgbEvaluator(),getCurrentColor(mProgress/100f,0xff40c7b6,0xffff7a59),getCurrentColor(progress/100f,0xff40c7b6,0xffff7a59));
animator.setDuration(duration);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Log.d("MainActivity", "animation.getAnimatedValue():" + animation.getAnimatedValue());
}
});
animator.start();
}
/**
* 根據(jù)fraction值來計(jì)算當(dāng)前的顏色虑润。 fraction值范圍 0f-1f
*/
private int getCurrentColor(float fraction, int startColor, int endColor) {
int redCurrent;
int blueCurrent;
int greenCurrent;
int alphaCurrent;
int redStart = Color.red(startColor);
int blueStart = Color.blue(startColor);
int greenStart = Color.green(startColor);
int alphaStart = Color.alpha(startColor);
int redEnd = Color.red(endColor);
int blueEnd = Color.blue(endColor);
int greenEnd = Color.green(endColor);
int alphaEnd = Color.alpha(endColor);
int redDifference = redEnd - redStart;
int blueDifference = blueEnd - blueStart;
int greenDifference = greenEnd - greenStart;
int alphaDifference = alphaEnd - alphaStart;
redCurrent = (int) (redStart + fraction * redDifference);
blueCurrent = (int) (blueStart + fraction * blueDifference);
greenCurrent = (int) (greenStart + fraction * greenDifference);
alphaCurrent = (int) (alphaStart + fraction * alphaDifference);
return Color.argb(alphaCurrent, redCurrent, greenCurrent, blueCurrent);
}
ok完事 保留 后期使用
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者