Android 绘制环形进度图

来源:互联网 发布:淘宝网mac版客户端 编辑:程序博客网 时间:2024/06/05 18:32

Android 绘制环形进度图
在项目中我们可能会遇见要画一个类似下面的环形进度图
这里写图片描述

分析怎么实现

  1. 需要2个空心圆 (一个是灰色,一个为绿色)
  2. 圆形里面需要添加文字

    我们在现实生活中比如需要画一幅画 来展示我们需要什么呢?
    画笔 画布 需要展示的地方

实现和详解

3.为了能够在一块特定的区域内进行绘画,首先实现了一个用于绘制图像的视图类PathView

 public class PahtView extends View {    public PahtView(Context context, AttributeSet attrs) {        DrawCircle(canvas);        super(context, attrs);    }    @Override    protected void onDraw(Canvas canvas) {    }   }}

Canvas :可以理解成一个画布
Paint:理解成一个画笔

绘制最下面灰色的空心圆
这里写图片描述

使用方法来实现

  public void drawArc(@NonNull RectF oval, float startAngle, float sweepAngle, boolean useCenter,            @NonNull Paint paint) {        drawArc(oval.left, oval.top, oval.right, oval.bottom, startAngle, sweepAngle, useCenter,                paint);    }
private void DrawCircle(Canvas canvas) {        // 创建一个画笔        Paint paint_backCircle = new Paint();        // 设置颜色        paint_backCircle.setColor(getResources().getColor(R.color.hs));        // 空心效果        paint_backCircle.setStyle(Style.STROKE);        // 设置环的宽        paint_backCircle.setStrokeWidth(5);        // 开始画圆        RectF mRectF = new RectF();       // 位置        mRectF.left = 20; // 左上角x        mRectF.top = 20; // 左上角y        mRectF.right = 110; // 左下角x        mRectF.bottom = 110; // 右下角y        //canvas.drawArc(0, 0, 70, paint_backCircle);        canvas.drawArc(mRectF, 0, 360, true, paint_backCircle);    }

这里我们详解哈RectF类 这里的 left top right bottom 不是上下左右
查询文档给出的解释如下

left The left side of the rectangle being tested for intersection
top The top of the rectangle being tested for intersection
right The right side of the rectangle being tested for intersection
bottom The bottom of the rectangle being tested for intersection

这里写图片描述

left : 图片中的A点
top: 图片中的C点
right : 图片中的B点
bottom: 图片中的D点

4.画第二个绿色圆

 private void DrawArc(Canvas canvas) {        RectF mRectF = new RectF();        mPaint = new Paint();        mPaint.setAntiAlias(true);        mPaint.setColor(getResources().getColor(R.color.ls));        canvas.drawColor(Color.TRANSPARENT);        mPaint.setStrokeWidth(5);        mPaint.setStyle(Style.STROKE);        // 位置        mRectF.left = 20; // 左上角x        mRectF.top = 20; // 左上角y        mRectF.right = 110; // 左下角x        mRectF.bottom = 110; // 右下角y        // 绘制圆圈,进度条背景        canvas.drawArc(mRectF, 120, 230, false, mPaint);    }

效果图片
这里写图片描述

5.插入字

    private void Darwcontent(Canvas canvas)    {        Paint paint_content = new Paint();        mPaint.setStyle(Style.FILL);        mPaint.setTextSize(20);        canvas.drawText("78.00%", 110 / 2-("78%".length()*6), 110 / 2 , paint_content);    }

运行效果如下

这里写图片描述

1 0