最近在项目总会用到一些圆形进度条,所以就记录下来 供以后可用
首先新建一个CircleProgressBar 继承View
package com.example.liwenjie.firstapp.viewbase; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; /** * Created by liwenjie on 2016/3/10 17:22 */ public class CircleProgressBar extends View { //设置最大值 private int maxProgress; //设置进度值 private int progress; //设置线宽 private int progressStrokeWidth; //设置线条颜色值 private int progressColor; //画圆所在的矩形 RectF oval; Paint paint; public CircleProgressBar(Context context) { super(context); } public CircleProgressBar(Context context, AttributeSet attrs) { super(context, attrs); oval = new RectF(); paint = new Paint(); } public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); super.onDraw(canvas); int width = this.getWidth(); int height = this.getHeight(); // 获取圆心的坐标 int centre = width / 2; if (width != height) { int min = Math.min(width, height); width = min; height = min; } paint.setAntiAlias(true); // 设置画笔为抗锯齿 paint.setColor(Color.WHITE); // 设置画笔颜色 canvas.drawColor(Color.TRANSPARENT); // 白色背景 paint.setStrokeWidth(progressStrokeWidth); // 线宽 paint.setStyle(Paint.Style.STROKE); oval.left = progressStrokeWidth / 2; // 左上角x oval.top = progressStrokeWidth / 2; // 左上角y oval.right = width - progressStrokeWidth / 2; // 左下角x oval.bottom = height - progressStrokeWidth / 2; // 右下角y canvas.drawArc(oval, -90, 360, false, paint); // 绘制白色圆圈,即进度条背景 //Color.rgb(81, 164, 247) paint.setColor(progressColor); canvas.drawArc(oval, -90, ((float) progress / maxProgress) * 360, false, paint); // 绘制进度圆弧,这里是蓝色 /*以下是在圆圈中间写字,看情况添加*/ /* paint.setStrokeWidth(1); String text = "√";//progress + "%"; int textHeight = height / 2; paint.setTextSize(textHeight); int textWidth = (int) paint.measureText(text, 0, text.length()); paint.setStyle(Paint.Style.FILL); canvas.drawText(text, centre - textWidth / 2, centre + textHeight/4,paint);*/ } public int getMaxProgress() { return maxProgress; } public void setMaxProgress(int maxProgress) { this.maxProgress = maxProgress; } public int getProgress() { return progress; } public void setProgress(int progress) { this.progress = progress; this.invalidate(); } public int getProgressStrokeWidth() { return progressStrokeWidth; } public void setProgressStrokeWidth(int progressStrokeWidth) { this.progressStrokeWidth = progressStrokeWidth; } /** * 非UI线程调用 */ public void setProgressNotInUiThread(int progress) { this.progress = progress; this.postInvalidate(); } public int getProgressColor() { return progressColor; } public void setProgressColor(int progressColor) { this.progressColor = progressColor; } }