Android利用属性动画自定义倒计时控件

简介:

本文介绍一下利用属性动画(未使用Timer,通过动画执行次数控制倒计时)自定义一个圆形倒计时控件,比较简陋,仅做示例使用,如有需要,您可自行修改以满足您的需求。控件中所使用的素材及配色均是笔者随意选择,导致效果不佳,先上示例图片

e5a3ffca8221e7d3a3e98cdb0f395a0f85c88b56

示例图片

示例中进度条底色、渐变色(仅支持两个色值)、字体大小、图片、进度条宽度及是否显示进度条等可通过xml修改,倒计时时间可通过代码设置。如果您感兴趣,可修改代码设置更丰富的渐变色值及文字变化效果,本文仅仅提供设计思路。

笔者利用属性动画多次执行实现倒计时,执行次数即为倒计时初始数值。对上述示例做一下拆解,会发现实现起来还是很容易的,需要处理的主要是以下几部分

1.绘制外部环形进度条

2.绘制中央旋转图片

3.绘制倒计时时间

一.绘制外部环形进度条,分为两部分:

1.环形背景 canvas.drawCircle方法绘制

2.扇形进度 canvas.drawArc方法绘制,弧度通过整体倒计时执行进度控制

二.绘制中央旋转图片:

前置描述:外层圆形直径设为d1;中央旋转图片直径设为d2;进度条宽度设为d3

1.将设置的图片进行剪切缩放处理(也可不剪切,笔者有强迫症),使其宽高等于d1 - 2 * d3,即d2 = d1 -  2 * d3;

2.利用Matrix将Bitmap平移至中央;

3.利用Matrix旋转Bitmap

三.绘制倒计时时间:

通过每次动画执行进度,控制文本位置

下面上示例代码:

public class CircleCountDownView extends View {
    private CountDownListener countDownListener;

    private int width;
    private int height;
    private int padding;
    private int borderWidth;
    // 根据动画执行进度计算出来的插值,用来控制动画效果,建议取值范围为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) {
                    // 监听剩余时间
                    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;
        // 设置重复执行次数,共执行initialCountDownValue次,恰好为倒计时总数
        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();
        // 圆形图片绘制区域半径
        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) {  
            // 绘制外层圆环
            canvas.drawCircle(centerX, centerY, Math.min(width, height) / 2 - borderWidth / 2 - padding, circleBorderPaint);
            if (showProgress) {
                // 绘制整体进度
                canvas.drawArc(circleProgressRectF, 0, 360 * totalTimeProgress, false, circleProcessPaint);
            }

        }
        // 设置图片旋转角度增量
        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();
        // 文字绘制基准线(圆形区域正中央)
        float verticalBaseline = (height - fontMetrics.bottom - fontMetrics.top) / 2;
        // 随动画执行进度而更新的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 {
        /**
         * 倒计时结束
         */

        void onCountDownFinish();

        /**
         * 倒计时剩余时间
         *
         * @param restTime 剩余时间,单位毫秒
         */

        void restTime(long restTime);
    }

    public interface AnimationInterpolator {
        /**
         * @param inputFraction 动画执行时间因子,取值范围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>

代码比较简单,如有疑问欢迎留言

原文发布时间为:2018-10-22

本文作者:乱世白衣

本文来自云栖社区合作伙伴“安卓巴士Android开发者门户”,了解相关信息可以关注“安卓巴士Android开发者门户”。



相关文章
|
Android开发 UED 计算机视觉
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
本文介绍了一款受游戏“金铲铲之战”启发的Android自定义View——线条等待动画的实现过程。通过将布局分为10份,利用`onSizeChanged`测量最小长度,并借助画笔绘制动态线条,实现渐变伸缩效果。动画逻辑通过四个变量控制线条的增长与回退,最终形成流畅的等待动画。代码中详细展示了画笔初始化、线条绘制及动画更新的核心步骤,并提供完整源码供参考。此动画适用于加载场景,提升用户体验。
861 5
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
|
Android开发
Android自定义view之利用PathEffect实现动态效果
本文介绍如何在Android自定义View中利用`PathEffect`实现动态效果。通过改变偏移量,结合`PathEffect`的子类(如`CornerPathEffect`、`DashPathEffect`、`PathDashPathEffect`等)实现路径绘制的动态变化。文章详细解析了各子类的功能与参数,并通过案例代码展示了如何使用`ComposePathEffect`组合效果,以及通过修改偏移量实现动画。最终效果为一个菱形图案沿路径运动,源码附于文末供参考。
337 0
|
Android开发 开发者
Android自定义view之利用drawArc方法实现动态效果
本文介绍了如何通过Android自定义View实现动态效果,重点使用`drawArc`方法完成圆弧动画。首先通过`onSizeChanged`进行测量,初始化画笔属性,设置圆弧相关参数。核心思路是不断改变圆弧扫过角度`sweepAngle`,并调用`invalidate()`刷新View以实现动态旋转效果。最后附上完整代码与效果图,帮助开发者快速理解并实践这一动画实现方式。
367 0
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
373 0
|
XML Java Android开发
Android自定义view之网易云推荐歌单界面
本文详细介绍了如何通过自定义View实现网易云音乐推荐歌单界面的效果。首先,作者自定义了一个圆角图片控件`MellowImageView`,用于绘制圆角矩形图片。接着,通过将布局放入`HorizontalScrollView`中,实现了左右滑动功能,并使用`ViewFlipper`添加图片切换动画效果。文章提供了完整的代码示例,包括XML布局、动画文件和Java代码,最终展示了实现效果。此教程适合想了解自定义View和动画效果的开发者。
620 65
Android自定义view之网易云推荐歌单界面
|
XML 前端开发 Android开发
一篇文章带你走近Android自定义view
这是一篇关于Android自定义View的全面教程,涵盖从基础到进阶的知识点。文章首先讲解了自定义View的必要性及简单实现(如通过三个构造函数解决焦点问题),接着深入探讨Canvas绘图、自定义属性设置、动画实现等内容。还提供了具体案例,如跑马灯、折线图、太极图等。此外,文章详细解析了View绘制流程(measure、layout、draw)和事件分发机制。最后延伸至SurfaceView、GLSurfaceView、SVG动画等高级主题,并附带GitHub案例供实践。适合希望深入理解Android自定义View的开发者学习参考。
1113 84
|
前端开发 Android开发 UED
讲讲Android为自定义view提供的SurfaceView
本文详细介绍了Android中自定义View时使用SurfaceView的必要性和实现方式。首先分析了在复杂绘制逻辑和高频界面更新场景下,传统View可能引发卡顿的问题,进而引出SurfaceView作为解决方案。文章通过Android官方Demo展示了SurfaceView的基本用法,包括实现`SurfaceHolder.Callback2`接口、与Activity生命周期绑定、子线程中使用`lockCanvas()`和`unlockCanvasAndPost()`方法完成绘图操作。
448 3
|
Android开发 开发者
Android自定义view之围棋动画(化繁为简)
本文介绍了Android自定义View的动画实现,通过两个案例拓展动态效果。第一个案例基于`drawArc`方法实现单次动画,借助布尔值控制动画流程。第二个案例以围棋动画为例,从简单的小球直线运动到双向变速运动,最终实现循环动画效果。代码结构清晰,逻辑简明,展示了如何化繁为简实现复杂动画,帮助读者拓展动态效果设计思路。文末提供完整源码,适合初学者和进阶开发者学习参考。
312 0
Android自定义view之围棋动画(化繁为简)
|
Java Android开发 开发者
Android自定义view之围棋动画
本文详细介绍了在Android中自定义View实现围棋动画的过程。从测量宽高、绘制棋盘背景,到创建固定棋子及动态棋子,最后通过属性动画实现棋子的移动效果。文章还讲解了如何通过自定义属性调整棋子和棋盘的颜色及动画时长,并优化视觉效果,如添加渐变色让白子更明显。最终效果既可作为围棋动画展示,也可用作加载等待动画。代码完整,适合进阶开发者学习参考。
432 0
|
传感器 Android开发 开发者
Android自定义view之3D正方体
本文介绍了如何通过手势滑动操作实现3D正方体的旋转效果,基于Android自定义View中的GLSurfaceView。相较于使用传感器控制,本文改用事件分发机制(onTouchEvent)处理用户手势输入,调整3D正方体的角度。代码中详细展示了TouchSurfaceView的实现,包括触控逻辑、OpenGL ES绘制3D正方体的核心过程,以及生命周期管理。适合对Android 3D图形开发感兴趣的开发者学习参考。
382 0

热门文章

最新文章