布局:
实现代码:<yaoming.test.com.testp2p.ui.RoundProgress android:layout_width="120dp" android:layout_height="120dp" android:layout_marginTop="10dp" />
public class RoundProgress extends View { private int width; private Paint paint; private float roundWidth = UIUtils.dp2px(10); private float max = 100; private float progress = 60; private int textSize = UIUtils.dp2px(20);//文本的字体大小 // private int public RoundProgress(Context context) { this(context, null); } public RoundProgress(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public RoundProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); paint.setAntiAlias(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //获取整个View的宽度 width = this.getMeasuredWidth(); } /** * @param canvas */ //Canvas:画布对应着视图在布局中的范围区间,范围的左上顶点即为坐标原点 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //1.绘制圆环 int cy = width / 2; //圆形的中心坐标 int cx = width / 2; //圆形的中心坐标 //设置半径的值要考虑到圆环的宽度,因为圆环的宽度是往外扩展的, // 半径的值加上圆环宽度的值会把整个圆形挤掉,超过外层正方矩形 float radius = width / 2 - roundWidth / 2; //半径 paint.setStyle(Paint.Style.STROKE); //设置圆环的样式 paint.setStrokeWidth(roundWidth); paint.setColor(Color.GRAY); canvas.drawCircle(cx, cy, radius, paint); //2.绘制圆弧(进度) //绘制一个与半径相同宽度的正方矩形 RectF rectF = new RectF(roundWidth / 2, roundWidth / 2, width - roundWidth / 2, width - roundWidth / 2); paint.setColor(Color.RED); canvas.drawArc(rectF, 0, progress / max * 360, false, paint); //3.绘制文本 paint.setColor(Color.BLUE); paint.setStrokeWidth(0); String text = progress * 100 / max + "%"; paint.setTextSize(textSize); Rect rect = new Rect(); paint.getTextBounds(text, 0, text.length(), rect);//此时的矩形的宽度和高度即为整好包裹文本的矩形的宽高
//获取左下顶点的坐标 int x = width / 2 - rect.width() / 2; int y = width / 2 + rect.height() / 2; canvas.drawText(text, x, y, paint); } }