Android利用屬性動畫自定義倒計時控件

本文介紹一下利用屬性動畫(未使用Timer,通過動畫執(zhí)行次數(shù)控制倒計時)自定義一個圓形倒計時控件,比較簡陋,僅做示例使用,如有需要,您可自行修改以滿足您的需求??丶兴褂玫乃夭募芭渖枪P者隨意選擇,導致效果不佳,先上示例圖片


示例中進度條底色、漸變色(僅支持兩個色值)、字體大小、圖片、進度條寬度及是否顯示進度條等可通過xml修改,倒計時時間可通過代碼設置。如果您感興趣,可修改代碼設置更豐富的漸變色值及文字變化效果,本文僅僅提供設計思路。

筆者利用屬性動畫多次執(zhí)行實現(xiàn)倒計時,執(zhí)行次數(shù)即為倒計時初始數(shù)值。對上述示例做一下拆解,會發(fā)現(xiàn)實現(xiàn)起來還是很容易的,需要處理的主要是以下幾部分
1.繪制外部環(huán)形進度條
2.繪制中央旋轉(zhuǎn)圖片
3.繪制倒計時時間

一.繪制外部環(huán)形進度條,分為兩部分:
1.環(huán)形背景 canvas.drawCircle方法繪制
2.扇形進度 canvas.drawArc方法繪制,弧度通過整體倒計時執(zhí)行進度控制

二.繪制中央旋轉(zhuǎn)圖片:
前置描述:外層圓形直徑設為d1;中央旋轉(zhuǎn)圖片直徑設為d2;進度條寬度設為d3
1.將設置的圖片進行剪切縮放處理(也可不剪切,筆者有強迫癥),使其寬高等于d1 - 2 * d3,即d2 = d1 - 2 * d3;
2.利用Matrix將Bitmap平移至中央;
3.利用Matrix旋轉(zhuǎn)Bitmap

三.繪制倒計時時間:
通過每次動畫執(zhí)行進度,控制文本位置

下面上示例代碼:

public class CircleCountDownView extends View {
    private CountDownListener countDownListener;

    private int width;
    private int height;
    private int padding;
    private int borderWidth;
    // 根據(jù)動畫執(zhí)行進度計算出來的插值,用來控制動畫效果,建議取值范圍為0到1
    private float currentAnimationInterpolation;
    private boolean showProgress;
    private float totalTimeProgress;
    private int processColorStart;
    private int processColorEnd;
    private int processBlurMaskRadius;

    private int initialCountDownValue;
    private int currentCountDownValue;

    private Paint circleBorderPaint;
    private Paint circleProcessPaint;
    private RectF circleProgressRectF;

    private Paint circleImgPaint;
    private Matrix circleImgMatrix;
    private Bitmap circleImgBitmap;
    private int circleImgRadius;
    private AnimationInterpolator animationInterpolator;
    private BitmapShader circleImgBitmapShader;
    private float circleImgTranslationX;
    private float circleImgTranslationY;
    private Paint valueTextPaint;

    private ValueAnimator countDownAnimator;

    public CircleCountDownView(Context context) {
        this(context, null);
    }

    public CircleCountDownView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleCountDownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        circleImgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        circleImgPaint.setStyle(Paint.Style.FILL);
        circleImgMatrix = new Matrix();
        valueTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CircleCountDownView);
        // 控制外層進度條的邊距
        padding = typedArray.getDimensionPixelSize(R.styleable.CircleCountDownView_padding, DisplayUtil.dp2px(5));
        // 進度條邊線寬度
        borderWidth = typedArray.getDimensionPixelSize(R.styleable.CircleCountDownView_circleBorderWidth, 0);
        if (borderWidth > 0) {
            circleBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            circleBorderPaint.setStyle(Paint.Style.STROKE);
            circleBorderPaint.setStrokeWidth(borderWidth);
            circleBorderPaint.setColor(typedArray.getColor(R.styleable.CircleCountDownView_circleBorderColor, Color.WHITE));

            showProgress = typedArray.getBoolean(R.styleable.CircleCountDownView_showProgress, false);
            if (showProgress) {
                circleProcessPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                circleProcessPaint.setStyle(Paint.Style.STROKE);
                circleProcessPaint.setStrokeWidth(borderWidth);
                // 進度條漸變色值
                processColorStart = typedArray.getColor(R.styleable.CircleCountDownView_processColorStart, Color.parseColor("#00ffff"));
                processColorEnd = typedArray.getColor(R.styleable.CircleCountDownView_processColorEnd, Color.parseColor("#35adc6"));
                // 進度條高斯模糊半徑
                processBlurMaskRadius = typedArray.getDimensionPixelSize(R.styleable.CircleCountDownView_processBlurMaskRadius, DisplayUtil.dp2px(5));
            }
        }


        int circleImgSrc = typedArray.getResourceId(R.styleable.CircleCountDownView_circleImgSrc, R.mipmap.ic_radar);
        // 圖片剪裁成正方形
        circleImgBitmap = ImageUtil.cropSquareBitmap(BitmapFactory.decodeResource(getResources(), circleImgSrc));

        valueTextPaint.setColor(typedArray.getColor(R.styleable.CircleCountDownView_valueTextColor, Color.WHITE));
        valueTextPaint.setTextSize(typedArray.getDimensionPixelSize(R.styleable.CircleCountDownView_valueTextSize, DisplayUtil.dp2px(13)));

        typedArray.recycle();

        // 初始化屬性動畫,周期為1秒
        countDownAnimator = ValueAnimator.ofFloat(0, 1).setDuration(1000);
        countDownAnimator.setInterpolator(new LinearInterpolator());
        countDownAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (countDownListener != null) {
                    // 監(jiān)聽剩余時間
                    long restTime = (long) ((currentCountDownValue - animation.getAnimatedFraction()) * 1000);
                    countDownListener.restTime(restTime);
                }
                // 整體倒計時進度
                totalTimeProgress = (initialCountDownValue - currentCountDownValue + animation.getAnimatedFraction()) / initialCountDownValue;
                if (animationInterpolator != null) {
                    currentAnimationInterpolation = animationInterpolator.getInterpolation(animation.getAnimatedFraction());
                } else {
                    currentAnimationInterpolation = animation.getAnimatedFraction();
                    currentAnimationInterpolation *= currentAnimationInterpolation;
                }
                invalidate();
            }
        });
        countDownAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationRepeat(Animator animation) {
                currentCountDownValue--;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (countDownListener != null) {
                    countDownListener.onCountDownFinish();
                }
            }
        });
    }

    // 設置倒計時初始時間
    public void setStartCountValue(int initialCountDownValue) {
        this.initialCountDownValue = initialCountDownValue;
        this.currentCountDownValue = initialCountDownValue;
        // 設置重復執(zhí)行次數(shù),共執(zhí)行initialCountDownValue次,恰好為倒計時總數(shù)
        countDownAnimator.setRepeatCount(currentCountDownValue - 1);
        invalidate();
    }

    public void setAnimationInterpolator(AnimationInterpolator animationInterpolator) {
        if (!countDownAnimator.isRunning()) {
            this.animationInterpolator = animationInterpolator;
        }
    }

    // 重置
    public void reset() {
        countDownAnimator.cancel();
        lastAnimationInterpolation = 0;
        totalTimeProgress = 0;
        currentAnimationInterpolation = 0;
        currentCountDownValue = initialCountDownValue;
        circleImgMatrix.setTranslate(circleImgTranslationX, circleImgTranslationY);
        circleImgMatrix.postRotate(0, width / 2, height / 2);
        invalidate();
    }

    public void restart() {
        reset();
        startCountDown();
    }

    public void pause() {
        countDownAnimator.pause();
    }

    public void setCountDownListener(CountDownListener countDownListener) {
        this.countDownListener = countDownListener;
    }

    //  啟動倒計時
    public void startCountDown() {
        if (countDownAnimator.isPaused()) {
            countDownAnimator.resume();
            return;
        }
        if (currentCountDownValue > 0) {
            countDownAnimator.start();
        } else if (countDownListener != null) {
            countDownListener.onCountDownFinish();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
        if (width > 0 && height > 0) {
            doCalculate();
        }
    }

    private void doCalculate() {
        circleImgMatrix.reset();
        // 圓形圖片繪制區(qū)域半徑
        circleImgRadius = (Math.min(width, height) - 2 * borderWidth - 2 * padding) / 2;
        float actualCircleImgBitmapWH = circleImgBitmap.getWidth();
        float circleDrawingScale = circleImgRadius * 2 / actualCircleImgBitmapWH;
        // bitmap縮放處理
        Matrix matrix = new Matrix();
        matrix.setScale(circleDrawingScale, circleDrawingScale, actualCircleImgBitmapWH / 2, actualCircleImgBitmapWH / 2);
        circleImgBitmap = Bitmap.createBitmap(circleImgBitmap, 0, 0, circleImgBitmap.getWidth(), circleImgBitmap.getHeight(), matrix, true);
        // 繪制圓形圖片使用
        circleImgBitmapShader = new BitmapShader(circleImgBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        // 平移至中心
        circleImgTranslationX = (width - circleImgRadius * 2) / 2;
        circleImgTranslationY = (height - circleImgRadius * 2) / 2;
        circleImgMatrix.setTranslate(circleImgTranslationX, circleImgTranslationY);

        if (borderWidth > 0) {
            // 外層進度條寬度(注意:需要減掉畫筆寬度)
            float circleProgressWH = Math.min(width, height) - borderWidth - 2 * padding;
            float left = (width > height ? (width - height) / 2 : 0) + borderWidth / 2 + padding;
            float top = (height > width ? (height - width) / 2 : 0) + borderWidth / 2 + padding;
            float right = left + circleProgressWH;
            float bottom = top + circleProgressWH;
            circleProgressRectF = new RectF(left, top, right, bottom);
            if (showProgress) {
                // 進度條漸變及邊緣高斯模糊處理
                circleProcessPaint.setShader(new LinearGradient(left, top, left + circleImgRadius * 2, top + circleImgRadius * 2, processColorStart, processColorEnd, Shader.TileMode.MIRROR));
                circleProcessPaint.setMaskFilter(new BlurMaskFilter(processBlurMaskRadius, BlurMaskFilter.Blur.SOLID)); // 設置進度條陰影效果
            }
        }
    }

    private float lastAnimationInterpolation;

    @Override
    protected void onDraw(Canvas canvas) {
        if (width == 0 || height == 0) {
            return;
        }
        int centerX = width / 2;
        int centerY = height / 2;
        if (borderWidth > 0) {  
            // 繪制外層圓環(huán)
            canvas.drawCircle(centerX, centerY, Math.min(width, height) / 2 - borderWidth / 2 - padding, circleBorderPaint);
            if (showProgress) {
                // 繪制整體進度
                canvas.drawArc(circleProgressRectF, 0, 360 * totalTimeProgress, false, circleProcessPaint);
            }

        }
        // 設置圖片旋轉(zhuǎn)角度增量
        circleImgMatrix.postRotate((currentAnimationInterpolation - lastAnimationInterpolation) * 360, centerX, centerY);
        circleImgBitmapShader.setLocalMatrix(circleImgMatrix);
        circleImgPaint.setShader(circleImgBitmapShader);
        canvas.drawCircle(centerX, centerY, circleImgRadius, circleImgPaint);
        lastAnimationInterpolation = currentAnimationInterpolation;

        // 繪制倒計時時間
        // current
        String currentTimePoint = currentCountDownValue + "s";
        float textWidth = valueTextPaint.measureText(currentTimePoint);
        float x = centerX - textWidth / 2;
        Paint.FontMetrics fontMetrics = valueTextPaint.getFontMetrics();
        // 文字繪制基準線(圓形區(qū)域正中央)
        float verticalBaseline = (height - fontMetrics.bottom - fontMetrics.top) / 2;
        // 隨動畫執(zhí)行進度而更新的y軸位置
        float y = verticalBaseline - currentAnimationInterpolation * (Math.min(width, height) / 2);
        valueTextPaint.setAlpha((int) (255 - currentAnimationInterpolation * 255));
        canvas.drawText(currentTimePoint, x, y, valueTextPaint);

        // next
        String nextTimePoint = (currentCountDownValue - 1) + "s";
        textWidth = valueTextPaint.measureText(nextTimePoint);
        x = centerX - textWidth / 2;
        y = y + (Math.min(width, height)) / 2;
        valueTextPaint.setAlpha((int) (currentAnimationInterpolation * 255));
        canvas.drawText(nextTimePoint, x, y, valueTextPaint);
    }

    public interface CountDownListener {
        /**
         * 倒計時結(jié)束
         */
        void onCountDownFinish();

        /**
         * 倒計時剩余時間
         *
         * @param restTime 剩余時間,單位毫秒
         */
        void restTime(long restTime);
    }

    public interface AnimationInterpolator {
        /**
         * @param inputFraction 動畫執(zhí)行時間因子,取值范圍0到1
         */
        float getInterpolation(float inputFraction);
    }
}

自定義屬性如下

<declare-styleable name="CircleCountDownView">
        <!--控件中間圖片資源-->
        <attr name="circleImgSrc" format="reference" />
        <attr name="circleBorderColor" format="color" />
        <attr name="circleBorderWidth" format="dimension" />
        <attr name="valueTextSize" format="dimension" />
        <attr name="valueTextColor" format="color" />
        <attr name="padding" format="dimension" />
        <attr name="showProgress" format="boolean" />
        <attr name="processColorStart" format="color" />
        <attr name="processColorEnd" format="color" />
        <attr name="processBlurMaskRadius" format="dimension" />
    </declare-styleable>

代碼比較簡單,如有疑問歡迎留言(貌似沒人看,沒人留言,我流汗~)
完整代碼:https://github.com/670832188/TestApp

靜態(tài)圖片
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容