如何动画渐变?

时间:2015-08-26 10:57:50

标签: android animation gradient android-custom-view ondraw

如何设置从颜色#1到颜色#2的渐变动画?类似于

的东西

enter image description here

我打算将它用作单位的健康栏(因此,它将是以绿色开头并以红色结尾的有限动画)

4 个答案:

答案 0 :(得分:27)

在谷歌搜索时,我找到了两种方法来为Android做use ShaderFactory或使用new Shader(new LinearGradient())扩展View。两个答案都是相同的 - 每次new Shader()方法调用都会调用View.onDraw(Canvas canvas)。如果这样的动画渐变数超过~3,它真的很贵。

所以我做了另一种方式。我使用单个预先计算的new避免每onDraw()次调用LinearGradient。这就是它的样子(gif,所以动画衰败了):

enter image description here

诀窍是创建LinearGradientcolorsCountView.getWidth()。之后,您可以在绘制渐变时使用canvas.translate()来更改其颜色,因此new中根本不会调用onDraw()

要创建渐变,您需要当前的宽度和高度。我在onSizeChanged()做了。我也在这里设置Shader

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    width = getWidth();
    height = getHeight();

    LinearGradient gradient = new LinearGradient(
            0, height / 2, width * colors.length - 1, height / 2,
            colors, null, Shader.TileMode.REPEAT);
    fillPaint.setShader(gradient);

    shapePath = getParallelogrammPath(width, height, sidesGap);
    shapeBorderPath = getParallelogrammPath(width, height, sidesGap);
}

我使用路径因为平行四边形视图,你可以使用你想要的任何东西。在实施绘图时,您应该注意两件事:您需要translate()整个canvas当前偏移量和offset()填充形状:

@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.translate(-gradientOffset, 0);
    shapePath.offset(gradientOffset, 0f, tempPath);
    canvas.drawPath(tempPath, fillPaint);
    canvas.restore();

    canvas.drawPath(shapeBorderPath, borderPaint);

    super.onDraw(canvas); // my View is FrameLayout, so need to call it after
}

另外你应该使用canvas.save()& canvas.restore()。它会将画布的内部矩阵保存到堆栈中并相应地恢复它。

所以你需要做的最后一件事是动画gradientOffset。您可以使用所需的所有内容,例如ObjectAnimator (Property Animation)。我使用TimeAnimator,因为我需要控制updateTick并直接开始偏移。这是我的认识(有点困难和苛刻):

static public final int LIFETIME_DEAFULT = 2300;
private long lifetime = LIFETIME_DEAFULT, updateTickMs = 25, timeElapsed = 0;
private long accumulatorMs = 0;
private float gradientOffset = 0f;

public void startGradientAnimation() {
    stopGradientAnimation();
    resolveTimeElapsed();

    final float gradientOffsetCoef = (float) (updateTickMs) / lifetime;
    final int colorsCount = this.colors.length - 1;
    gradientAnimation.setTimeListener(new TimeAnimator.TimeListener() {
        @Override
        public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) {
            final long gradientWidth = width * colorsCount;
            if (totalTime > (lifetime - timeElapsed)) {
                animation.cancel();
                gradientOffset = gradientWidth;
                invalidate();
            } else {
                accumulatorMs += deltaTime;

                final long gradientOffsetsCount = accumulatorMs / updateTickMs;
                gradientOffset += (gradientOffsetsCount * gradientWidth) * gradientOffsetCoef;
                accumulatorMs %= updateTickMs;

                boolean gradientOffsetChanged = (gradientOffsetsCount > 0) ? true : false;
                if (gradientOffsetChanged) {
                    invalidate();
                }
            }
        }
    });

    gradientAnimation.start();
}

您可以找到完整的View代码here

答案 1 :(得分:9)

我想出了另一种更短的方法。只需使用setColors (int[] colors)的{​​{1}}方法并对其进行动画处理即可。

这是一个示例操作方法:

GradientDrawable

结果:

enter image description here

答案 2 :(得分:4)

只是重写了@Krzysztof Misztal对java的回答:

public static void startAnimation(final int view, final Activity activity) {
        final int start = Color.parseColor("#FDB72B");
        final int mid = Color.parseColor("#88FDB72B");
        final int end = Color.TRANSPARENT;


        final ArgbEvaluator evaluator = new ArgbEvaluator();
        View preloader = activity.findViewById(R.id.gradientPreloaderView);
        preloader.setVisibility(View.VISIBLE);
        final GradientDrawable gradient = (GradientDrawable) preloader.getBackground();

        ValueAnimator animator = TimeAnimator.ofFloat(0.0f, 1.0f);
        animator.setDuration(500);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Float fraction = valueAnimator.getAnimatedFraction();
                int newStrat = (int) evaluator.evaluate(fraction, start, end);
                int newMid = (int) evaluator.evaluate(fraction, mid, start);
                int newEnd = (int) evaluator.evaluate(fraction, end, mid);
                int[] newArray = {newStrat, newMid, newEnd};
                gradient.setColors(newArray);
            }
        });

        animator.start();
    }




public static void stopAnimation(final int view, final Activity activity){

    ObjectAnimator.ofFloat(activity.findViewById(view), "alpha", 0f).setDuration(125).start();
}

其中view是具有渐变背景的简单View

//gradient_preloader
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FDB72B"
        android:endColor="#00000000"
        android:angle="0"/>
</shape>

视图:

<View
    android:id="@+id/gradientPreloaderView"
    android:layout_width="match_parent"
    android:visibility="gone"
    android:layout_height="@dimen/basic_8_dp"
    android:background="@drawable/gradient_preloader" />

希望我的回答会有所帮助

答案 3 :(得分:1)

最新的替代答案。

class GradientAnimationDrawable(
  start: Int = Color.rgb(0, 143, 209),
  center: Int = Color.rgb(1, 106, 154),
  end: Int = Color.rgb(28, 179, 249),
  frameDuration: Int = 3000,
  enterFadeDuration: Int = 0,
  exitFadeDuration: Int = 3000
) : AnimationDrawable() {

  private val gradientStart = GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, intArrayOf(start, center, end))
    .apply {
      shape = GradientDrawable.RECTANGLE
      gradientType = GradientDrawable.LINEAR_GRADIENT
    }

  private val gradientCenter = GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, intArrayOf(center, end, start))
    .apply {
      shape = GradientDrawable.RECTANGLE
      gradientType = GradientDrawable.LINEAR_GRADIENT
    }

  private val gradientEnd = GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, intArrayOf(end, start, center))
    .apply {
      shape = GradientDrawable.RECTANGLE
      gradientType = GradientDrawable.LINEAR_GRADIENT
    }

  init {
    addFrame(gradientStart, frameDuration)
    addFrame(gradientCenter, frameDuration)
    addFrame(gradientEnd, frameDuration)
    setEnterFadeDuration(enterFadeDuration)
    setExitFadeDuration(exitFadeDuration)
    isOneShot = false
  }

}