我有一个 TextView
并且其中有一些文本。我需要创建一个持续30秒的动画,它会缓慢地将文本的颜色从绿色变成红色。有什么想法吗?
1) 30秒是很长的时间,几乎没有用户会等待它的结束。
2) 请参见使用ObjectAnimator进行动画处理。像ObjectAnimator.ofInt(textView, "textColor", Color.GREEN, Color.RED)
这样的代码应该能够满足您的需求。但请注意,过渡将是线性的,并且将经过许多中间颜色,直到达到#FF0000
。当然,您可以指定中间点,但一般来说,RGB颜色线性过渡并不美观。
Delyan的解决方案可以工作,但是正如他所指出的那样,颜色转换不够平滑。以下代码应该能够给您提供平滑的颜色转换:
public static void changeTextColor(final TextView textView, int startColor, int endColor,
final long animDuration, final long animUnit){
if (textView == null) return;
final int startRed = Color.red(startColor);
final int startBlue = Color.blue(startColor);
final int startGreen = Color.green(startColor);
final int endRed = Color.red(endColor);
final int endBlue = Color.blue(endColor);
final int endGreen = Color.green(endColor);
new CountDownTimer(animDuration, animUnit){
//animDuration is the time in ms over which to run the animation
//animUnit is the time unit in ms, update color after each animUnit
@Override
public void onTick(long l) {
int red = (int) (endRed + (l * (startRed - endRed) / animDuration));
int blue = (int) (endBlue + (l * (startBlue - endBlue) / animDuration));
int green = (int) (endGreen + (l * (startGreen - endGreen) / animDuration));
Log.d("Changing color", "Changing color to RGB" + red + ", " + green + ", " + blue);
textView.setTextColor(Color.rgb(red, green, blue));
}
@Override
public void onFinish() {
textView.setTextColor(Color.rgb(endRed, endGreen, endBlue));
}
}.start();
}
setEvaluator(new ArgbEvaluator());
为了消除闪烁现象,以下代码将使文本视图“tv”每30,000毫秒从绿色渐变到红色,而不会出现任何紧张的闪烁:
public void animateIt(){
ObjectAnimator a = ObjectAnimator.ofInt(tv, "textColor", Color.GREEN, Color.RED);
a.setInterpolator(new LinearInterpolator());
a.setDuration(30000);
a.setRepeatCount(ValueAnimator.INFINITE);
a.setRepeatMode(ValueAnimator.REVERSE);
a.setEvaluator(new ArgbEvaluator());
AnimatorSet t = new AnimatorSet();
t.play(a);
t.start();
}
标签,可以考虑使用其他方法来实现。
ObjectAnimator a = ObjectAnimator.ofInt(...)
ObjectAnimator a = ObjectAnimator.ofArgb(...)