如何设置渐变动画?

ej83mcc0  于 2021-06-29  发布在  Java
关注(0)|答案(4)|浏览(482)

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

我计划用它作为单位的健康栏(所以,它将是以绿色开始,以红色结束的有限动画)

cfh9epnr

cfh9epnr1#

我想出了不同的,短得多的方法。简单使用 setColors (int[] colors) 方法 GradientDrawable 并随着时间的推移将其动画化。
这是一个如何做到这一点的例子:

val start = Color.DKGRAY
val mid = Color.MAGENTA
val end = Color.BLUE

//content.background is set as a GradientDrawable in layout xml file 
val gradient = content.background as GradientDrawable

val evaluator = ArgbEvaluator()
val animator = TimeAnimator.ofFloat(0.0f, 1.0f)
animator.duration = 1500
animator.repeatCount = ValueAnimator.INFINITE
animator.repeatMode = ValueAnimator.REVERSE
animator.addUpdateListener {
    val fraction = it.animatedFraction
    val newStart = evaluator.evaluate(fraction, start, end) as Int
    val newMid = evaluator.evaluate(fraction, mid, start) as Int
    val newEnd = evaluator.evaluate(fraction, end, mid) as Int

    gradient.colors = intArrayOf(newStart, newMid, newEnd)
}

animator.start()

结果是:

kse8i1jr

kse8i1jr2#

刚刚重写了@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" />

希望我的回答能有所帮助

j7dteeu8

j7dteeu83#

在谷歌上搜索时,我发现了两种android的方法:使用shaderfactory或extends view,使用 new Shader(new LinearGradient()) . 两个答案都是一样的 new Shader()View.onDraw(Canvas canvas) 方法的调用。如果这样的动画渐变的数量超过~3,那么它就非常昂贵。
所以我换了个方法。我没有打电话 newonDraw() ,使用单个预先计算 LinearGradient . 这就是它的样子(gif,所以动画衰减了):

诀窍是创造 LinearGradient 哪个是 colorsCount 倍于 View.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(属性动画)。我用了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 代码可以在这里找到

zhte4eai

zhte4eai4#

最新的替代答案。

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
  }

}

相关问题