15

我有一个TextView和一些文本。我需要创建一个持续时间为 30 秒的动画,它会慢慢地将文本的颜色从绿色变为红色。有任何想法吗?

4

3 回答 3

27

1) 30 年代是一个非常非常长的时间,几乎没有用户会等着看它的结束。

2) 参见使用 ObjectAnimator 制作动画。类似的东西ObjectAnimator.ofInt(textView, "textColor", Color.GREEN, Color.RED)应该做你想做的事。但是请注意,过渡将是线性的,并且会经过很多中间颜色。直到它击中#FF0000。您当然可以指定中间的点,但通常线性颜色过渡(在 RGB 中)并不漂亮。

于 2013-10-06T10:27:10.443 回答
2

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();
}
于 2016-11-03T21:11:38.850 回答
2

如上所述,使用

setEvaluator(new ArgbEvaluator());

消除闪烁。以下将每 30,000 毫秒将 textview“tv”从绿色淡化为红色,而不会出现任何紧张的闪烁:

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();
}
于 2017-09-24T18:34:23.313 回答