Подтвердить что ты не робот

Как создать анимацию с изменением цвета? (Android)

У меня есть TextView и некоторый текст в нем. Мне нужно создать анимацию продолжительностью 30 секунд, и она будет медленно менять цвет текста с зеленого на красный. Любые идеи?

4b9b3361

Ответ 1

1) 30s - действительно, действительно долгое время, вряд ли кто-нибудь будет ждать, чтобы увидеть его конец.

2) См. Анимация с помощью ObjectAnimator. Что-то вроде ObjectAnimator.ofInt(textView, "textColor", Color.GREEN, Color.RED) должно делать то, что вы хотите. Заметим, однако, что переход будет линейным и пройдет много промежуточных цветов. пока он не достигнет #FF0000. Конечно, вы можете указать точки в середине, но в целом линейные цветовые переходы (в RGB) не очень хороши.

Ответ 2

Решение Деляна работает, но, как он отметил, переход цвета не является гладким. Следующий код должен обеспечить плавный переход цвета:

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

чтобы устранить мигание. Следующее приведет к постепенному исчезновению текста "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();
}