android自定义View控件——圆形进度条

项目中用到这种自定义的进度条,把代码提取出来,方便以后查找继续使用,哈哈。
效果图:


android自定义View控件——圆形进度条_第1张图片

底部文字需要绘制圆角背景,需要用到drawRoundRect(),该方法用于在画布上绘制圆角矩形,通过指定RectF对象以及圆角半径来实现。该方法是绘制圆角矩形的主要方法,同时也可以通过设置画笔的空心效果来绘制空心的圆角矩形。
【基本语法】public void drawRoundRect (RectF rect, float rx, float ry, Paint paint)
参数说明
rect:RectF对象。
rx:x方向上的圆角半径。
ry:y方向上的圆角半径。
paint:绘制时所使用的画笔。

自定义view的类CircleProgressView:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;
        radius = centerX-stokeWidth/2;
        canvas.drawCircle(centerX, centerY, radius, mCirPaint);
        //画圆
        RectF rectF=new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
        canvas.drawArc(rectF, -90, progress * 360 / 100, false, mArcPaint);
        //设置中心文本
        if (null != centerText) {
            canvas.drawText(centerText, centerX - (mTextCenterPaint.measureText(centerText)) / 2, centerY + mTextCenterSize / 2, mTextCenterPaint);
        }
        //上方文字
        if (null != topText) {
            canvas.drawText(topText, centerX - (mTextTopPaint.measureText(topText)) / 2, centerY - mTextCenterSize, mTextTopPaint);
        }
        //最上方小文字
        if(null !=topFloorText){
            canvas.drawText(topFloorText,getWidth()-mTextCenterPaint.measureText(topFloorText),centerY-mTextCenterSize-mTextTopSize, mTextTopFloorPaint);
        }
        if (null != bottomText) {
            //下方圆角矩形
            Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(bottomTextColor);
            RectF rec = new RectF(centerX - (mTextBottomPaint.measureText(bottomText)) / 2-DensityUtil.dip2px(mContext,6),
                    getHeight()-centerY/2-mTextBottomSize,
                    centerX +(mTextBottomPaint.measureText(bottomText)) / 2+DensityUtil.dip2px(mContext,6),
                    getHeight()-(centerY)/2+mTextBottomSize/2);
            canvas.drawRoundRect(rec,10, 10, paint);    //第二个参数是x半径,第三个参数是y半径
            //下方文字
            canvas.drawText(bottomText,centerX - (mTextBottomPaint.measureText(bottomText)) / 2, getHeight()-(centerY)/2, mTextBottomPaint);
        }
    }

布局文件代码:

    

activity中设置progress相关属性

     circleProgressView= (CircleProgressView) findViewById(R.id.progress_view);
        circleProgressView.setTopFloorText("小文字");
        circleProgressView.setTopText("上方文字");
        circleProgressView.setCenterText("中间文字");
        circleProgressView.setBottomText("下方文字");
        circleProgressView.setProgress(80);
        circleProgressView.setSpeed(40);

以后会继续添加。源码地址:https://github.com/yinsujun/CircularProgress

你可能感兴趣的:(android自定义View控件——圆形进度条)