Android ValueAnimator用ArgbEvaluator做颜色渐变出现彩虹色异常怎么解决
Android TextView 背景色渐变淡入异常修复方案
需求为选中目标颜色后,TextView 背景从透明状态平滑过渡到目标色,原有实现代码运行后未出现预期的深浅渐变效果,反而出现彩虹色异常插值过程,仅最终值为正确目标色。应用 minSDK 为 16,无法使用ValueAnimator.ofArgb()方法。
原有问题代码
ValueAnimator anim = new ValueAnimator(); anim.setEvaluator(ArgbEvaluator.getInstance()); anim.setDuration(1500); anim.setIntValues(hightlightColor & 0x00FFFFFF, hightlightColor); anim.addUpdateListener(animation -> txtView.setBackgroundColor((int) animation.getAnimatedValue())); anim.start();
问题原因
ArgbEvaluator需要对ARGB四个通道分别做线性插值,使用setIntValues传入颜色值时,低版本系统会直接对int整数值做插值计算,不会按ARGB通道拆分处理,导致中间生成杂色。- TextView 初始背景为 null 时,首次赋值带 alpha 通道的颜色会出现绘制异常,放大插值杂色的表现。
修复方案
修复步骤
- 提前给 TextView 设置初始透明背景,避免从无背景状态过渡的绘制问题。
- 将
setIntValues替换为setObjectValues传入颜色值,保证ArgbEvaluator可以正确拆分ARGB通道做插值。 - 如果仍存在绘制异常,可临时开启 TextView 的软件渲染规避硬件加速兼容性问题。
修复后代码
// 可选:开启软件渲染,规避硬件加速对alpha通道颜色的绘制兼容问题 // txtView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // 初始化背景为透明 txtView.setBackgroundColor(Color.TRANSPARENT); ValueAnimator anim = new ValueAnimator(); anim.setEvaluator(ArgbEvaluator.getInstance()); anim.setDuration(1500); // 构造起始色:保留目标色的RGB通道,alpha通道设为0 int startColor = hightlightColor & 0x00FFFFFF; int endColor = hightlightColor; // 使用setObjectValues传入颜色值 anim.setObjectValues(startColor, endColor); anim.addUpdateListener(animation -> txtView.setBackgroundColor((int) animation.getAnimatedValue())); anim.start();
内容的提问来源于stack exchange,提问作者Rafael Lima
相关产品推荐
相关产品推荐

