如何创建颜色变化动画?(Android)

15

我有一个 TextView 并且其中有一些文本。我需要创建一个持续30秒的动画,它会缓慢地将文本的颜色从绿色变成红色。有什么想法吗?


如果您想使用偏移而不是动画来混合颜色,请查看我的答案:https://dev59.com/8G025IYBdhLWcg3wVkYR#24285364 - Marqs
你可以参考这个答案:https://dev59.com/r3E85IYBdhLWcg3wx2n2#34429554 - RBK
4个回答

27

1) 30秒是很长的时间,几乎没有用户会等待它的结束。

2) 请参见使用ObjectAnimator进行动画处理。像ObjectAnimator.ofInt(textView, "textColor", Color.GREEN, Color.RED)这样的代码应该能够满足您的需求。但请注意,过渡将是线性的,并且将经过许多中间颜色,直到达到#FF0000。当然,您可以指定中间点,但一般来说,RGB颜色线性过渡并不美观。


2
使用 anim.setEvaluator(new ArgbEvaluator())来避免闪烁。 - Adrian

3

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();
}

2
如上所述,请使用。
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();
}

0
也许我可以在pollaris的回答上进行补充。不要使用

标签,可以考虑使用其他方法来实现。

ObjectAnimator a = ObjectAnimator.ofInt(...)

您可以使用以下替代方式:
ObjectAnimator a = ObjectAnimator.ofArgb(...)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接