Android之Color 颜色过度计算

在MIUI上看到很多颜色渐变动画,感觉很炫,用ObjectAnimator试了一下能实现初步效果,一下是源代码

使用ObjectAnimator实现颜色渐变动画

        ObjectAnimator  animator = ObjectAnimator.ofObject(testLayout, "backgroundColor",new ArgbEvaluator(),0xff40c7b6,0xffff7a59);
        animator.setDuration(1000);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();

看起来很容易,但是我留意到进度条变化的时候背景颜色跟着一起变化,用这个方法只能能实现从某个颜色变化到某个颜色并不能在中间停顿保留,我上网搜索了下,很多大佬使用的是自定义TypeEvaluator来计算属性动画的属性值,但是想实现停留在中的颜色还是停留不了,于是我拿DALAO的代码进行了一部分抽离

public void startValueAnimator(int progress,int mProgress){
        if(animator != null && animator.isRunning()){
            animator.cancel();
            animator = null;
        }
        int duration = 15 * Math.abs(progress - mProgress);
        animator = ObjectAnimator.ofObject(testLayout, "backgroundColor",new ArgbEvaluator(),getCurrentColor(mProgress/100f,0xff40c7b6,0xffff7a59),getCurrentColor(progress/100f,0xff40c7b6,0xffff7a59));
        animator.setDuration(duration);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.d("MainActivity", "animation.getAnimatedValue():" + animation.getAnimatedValue());
            }
        });
        animator.start();
    }
/**
     * 根据fraction值来计算当前的颜色。 fraction值范围  0f-1f
     */
    private int getCurrentColor(float fraction, int startColor, int endColor) {
        int redCurrent;
        int blueCurrent;
        int greenCurrent;
        int alphaCurrent;

        int redStart = Color.red(startColor);
        int blueStart = Color.blue(startColor);
        int greenStart = Color.green(startColor);
        int alphaStart = Color.alpha(startColor);

        int redEnd = Color.red(endColor);
        int blueEnd = Color.blue(endColor);
        int greenEnd = Color.green(endColor);
        int alphaEnd = Color.alpha(endColor);

        int redDifference = redEnd - redStart;
        int blueDifference = blueEnd - blueStart;
        int greenDifference = greenEnd - greenStart;
        int alphaDifference = alphaEnd - alphaStart;

        redCurrent = (int) (redStart + fraction * redDifference);
        blueCurrent = (int) (blueStart + fraction * blueDifference);
        greenCurrent = (int) (greenStart + fraction * greenDifference);
        alphaCurrent = (int) (alphaStart + fraction * alphaDifference);

        return Color.argb(alphaCurrent, redCurrent, greenCurrent, blueCurrent);
    }

ok完事 保留 后期使用

你可能感兴趣的:(Android之Color 颜色过度计算)