Android圆形进度条

圆形进度条.jpg
先在attrs.xml中自定义属性
<declare-styleable name="CircleProgressBar">
        <attr name="backgroundColor" format="color" />
        <attr name="progressColor" format="color" />
        <attr name="progressWidth" format="dimension" />
        <attr name="maxProgress" format="integer" />
        <attr name="radius" format="dimension" />
        <attr name="android:textSize" format="dimension" />
        <attr name="android:textColor" format="color"/>
    </declare-styleable>
初始化一些参数
private void init() {
        setRadius_px(radius_px);

        bgPaint.setAntiAlias(true);
        bgPaint.setColor(backgroundColor);
        bgPaint.setStrokeWidth(progressWidth);
        bgPaint.setStyle(Paint.Style.STROKE);

        pgPaint.setAntiAlias(true);
        pgPaint.setColor(progressColor);
        pgPaint.setStrokeWidth(progressWidth);
        pgPaint.setStyle(Paint.Style.STROKE);
        pgPaint.setStrokeCap(Paint.Cap.ROUND);

        textPaint.setAntiAlias(true);
        textPaint.setColor(textColor);
        textPaint.setTextSize(textSize);
    }
在onDraw()方法中调用下面方法
private void drawBgProgress(Canvas canvas) {
        canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, radius_px, bgPaint);
    }

    private void drawProgress(Canvas canvas) {
        float left, top, right, bottom;
        int centerX = getMeasuredWidth() / 2;
        int centerY = getMeasuredHeight() / 2;
        left = centerX - radius_px;
        top = centerY - radius_px;
        right = centerX + radius_px;
        bottom = centerY + radius_px;
        RectF rectF = new RectF(left, top, right, bottom);
        canvas.drawArc(rectF, 0, 360f * progress / maxProgress, false, pgPaint);
    }

    private void drawText(Canvas canvas) {
        Paint.FontMetrics m = new Paint.FontMetrics();
        textPaint.getFontMetrics(m);
        int baseLine = (int) (getMeasuredHeight() / 2 - (m.top + m.bottom) / 2);

        String text = (int) ((float) progress / maxProgress * 100) + "%";
        canvas.drawText(text, getMeasuredWidth() / 2 - textPaint.measureText(text) / 2, baseLine, textPaint);
    }
项目地址:https://gitee.com/aruba/CircleProgressBar.git
posted @ 2019-12-31 09:46  aruba_233  阅读(22)  评论(0)    收藏  举报