【问题标题】:How to create color changing animation? (Android)如何制作变色动画? (安卓)
【发布时间】:2013-10-13 00:24:52
【问题描述】:

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

【问题讨论】:

标签: android animation colors textview


【解决方案1】:

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

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

【讨论】:

  • 您的回答很有帮助!非常感谢!
  • 使用 anim.setEvaluator(new ArgbEvaluator()) 避免闪烁。
【解决方案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();
}

【讨论】:

    【解决方案3】:

    如上所述,使用

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

    【讨论】:

      猜你喜欢
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 2011-11-15
      • 2011-12-04
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多