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

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

3 ответов


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

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


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

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

Как указано выше, используйте

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