Android1对1直播源码实现颜色渐变动画效果

Android1对1直播源码实现颜色渐变动画效果的相关代码
1.利用Android自带的颜色估值器ArgbEvaluator

ValueAnimator colorAnim = ObjectAnimator.ofInt(this, "backgroundColor", RED, BLUE);
colorAnim.setDuration(4000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();

 



2.看看Android自带颜色估值器ArgbEvaluator核心代码

@Override
public Object evaluate(float fraction, Object startValue, Object endValue) {
int startInt = (Integer) startValue;
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;

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;

// 将sRGB转化成线性
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);

//在线性空间中计算插值的颜色
float a = startA + fraction * (endA - startA);
float r = startR + fraction * (endR - startR);
float g = startG + fraction * (endG - startG);
float b = startB + fraction * (endB - startB);

//转换回sRGB在[0..255]范围
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);
}

 

3.根据ArgbEvaluator的实现来自定义一个颜色估值器

 

public class MyColorEvaluator implements TypeEvaluator

 


 

接下来换一种颜色的计算方式,在本人看相关api的过程中,发现Color中有colorToHSV和HSVToColor的方法,于是在网上找了一个HVS的计算方式。

 

@Override
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
Color.colorToHSV(startValue,startHsv);
Color.colorToHSV(endValue,endHsv);
int alpha = startValue >> 24 + (int) ((endValue >> 24 - startValue >> 24) * fraction);
// 计算当前动画完成度(fraction)所对应的颜色值
if (endHsv[0] - startHsv[0] > 180) {
endHsv[0] -= 360;
} else if (endHsv[0] - startHsv[0] < -180) {
endHsv[0] += 360;
}
outHsv[0] = startHsv[0] + (endHsv[0] - startHsv[0]) * fraction;
if (outHsv[0] > 360) {
outHsv[0] -= 360;
} else if (outHsv[0] < 0) {
outHsv[0] += 360;
}
outHsv[1]=startHsv[1]+(endHsv[1]-startHsv[1])*fraction;
outHsv[2]=startHsv[2]+(endHsv[2]-startHsv[2])*fraction;


return Color.HSVToColor(alpha,outHsv);

}

 

4.使用自己定义的颜色插值器MyColorEvaluator

ValueAnimator colorAnim = ObjectAnimator.ofInt(this, "backgroundColor", RED, BLUE);
colorAnim.setDuration(4000);
colorAnim.setEvaluator(new MyColorEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();

 

以上就是Android1对1直播源码实现颜色渐变动画效果的相关代码, 更多内容欢迎关注之后的文章

posted @ 2021-08-26 14:08  云豹科技-苏凌霄  阅读(63)  评论(0编辑  收藏  举报