如何创建变色动画? (机器人)

时间:2013-10-06 10:20:42

标签: android animation colors textview

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

3 个答案:

答案 0 :(得分:26)

1)30s是一个非常非常长的时间,几乎没有任何用户会等待看到它的结束。

2)见Animating with ObjectAnimator。像ObjectAnimator.ofInt(textView, "textColor", Color.GREEN, Color.RED)这样的东西应该做你想要的。但请注意,转换将是线性的,并将经历许多中间色。直到它达到#FF0000。您当然可以在中间指定点,但通常线性颜色过渡(RGB)并不漂亮。

答案 1 :(得分:1)

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 :(得分:1)

如上所述,使用

setEvaluator(new ArgbEvaluator());

消除眨眼。以下内容将淡化textview" 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();
}