下面示例為view的背景色在3s內(nèi)從透明度100%的紅色到透明度為60%的綠色進(jìn)行過渡變化,此處view和為任何View
ValueAnimator animator = ObjectAnimator.ofInt(view, "backgroundColor", 0x00ff0000, 0x6600ff00);//對背景色顏色進(jìn)行改變,操作的屬性為"backgroundColor",此處必須這樣寫,不能全小寫,后面的顏色為在對應(yīng)顏色間進(jìn)行漸變
animator.setDuration(3000);
animator.setEvaluator(new ArgbEvaluator());//如果要顏色漸變必須要ArgbEvaluator,來實現(xiàn)顏色之間的平滑變化,否則會出現(xiàn)顏色不規(guī)則跳動
animator.start();
ArgbEvaluator
/**
*顏色演變核心算法
* fraction:動畫過渡時間因子罪既,決定了動畫變化的速率,值為0-1之間
* startvalue:動畫起始顏色
* endValue:動畫結(jié)束顏色
*/
public Object evaluate(float fraction, Object startValue, Object endValue) {
int startInt = (Integer) startValue;
/*
* 起始顏色ARGB顏色通道拆分
*/
float startA = ((startInt >> 24) & 0xff) / 255.0f;
float startR = ((startInt >> 16) & 0xff) / 255.0f;
float startG = ((startInt >> 8) & 0xff) / 255.0f;
float startB = ( startInt & 0xff) / 255.0f;
/*
* 結(jié)束顏色ARGB顏色通道拆分
*/
int endInt = (Integer) endValue;
float endA = ((endInt >> 24) & 0xff) / 255.0f;
float endR = ((endInt >> 16) & 0xff) / 255.0f;
float endG = ((endInt >> 8) & 0xff) / 255.0f;
float endB = ( endInt & 0xff) / 255.0f;
// convert from sRGB to linear
startR = (float) Math.pow(startR, 2.2);
startG = (float) Math.pow(startG, 2.2);
startB = (float) Math.pow(startB, 2.2);
endR = (float) Math.pow(endR, 2.2);
endG = (float) Math.pow(endG, 2.2);
endB = (float) Math.pow(endB, 2.2);
/*
*根據(jù)動畫時間因子,計算出中間的過渡顏色
*/
// compute the interpolated color in linear space
float a = startA + fraction * (endA - startA);
float r = startR + fraction * (endR - startR);
float g = startG + fraction * (endG - startG);
float b = startB + fraction * (endB - startB);
// convert back to sRGB in the [0..255] range
a = a * 255.0f;
r = (float) Math.pow(r, 1.0 / 2.2) * 255.0f;
g = (float) Math.pow(g, 1.0 / 2.2) * 255.0f;
b = (float) Math.pow(b, 1.0 / 2.2) * 255.0f;
/*
*重新將分離的顏色通道組合返回過渡顏色
*/
return Math.round(a) << 24 | Math.round(r) << 16 | Math.round(g) << 8 | Math.round(b);
}