自定义圆环精度条
(本文主要描述画圆的核心内容,其余的属性自己扩展)
1继承View 初始化
2测量画布的大小
3绘制圆环
4绘制圆弧
5绘制文字
public class Rund extends View { private Paint paint; private int now=20; 当前进度 private int max=200;最大进度 private Rect rect; private int rundwidth=60;//圆弧宽度 private int measuredWidth; public Rund(Context context) { this(context,null); } public Rund(Context context, AttributeSet attrs) { this(context, attrs,0); } public Rund(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化 initView(); } private void initView() { paint = new Paint();//创建笔 rect=new Rect();//创建矩形 this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { now--; if(now<=0){ now=0; } invalidate();//强制重绘 } }); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //MeasureSpec. measuredWidth = getMeasuredWidth();//测量当前画布大小 } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setStyle(Paint.Style.STROKE);//设置为空心圆 paint.setStrokeWidth(rundwidth); paint.setColor(Color.RED); float x = measuredWidth / 2; float y = measuredWidth / 2; int rd = measuredWidth / 2 - rundwidth / 2; canvas.drawCircle(x, y, rd, paint); //绘制圆弧 RectF rectF = new RectF(rundwidth/2,rundwidth/2,measuredWidth-rundwidth/2,measuredWidth-rundwidth/2); paint.setColor(Color.BLUE); canvas.drawArc(rectF,0,now*360/max,false,paint); //设置当前文字 String text=now*100/max+"%"; paint.setStrokeWidth(0); Rect rect = new Rect(); paint.setTextSize(90); paint.getTextBounds(text,0,text.length(),rect); paint.setColor(Color.BLACK); canvas.drawText(text,measuredWidth/2-rect.width()/2,measuredWidth/2+rect.height()/2,paint); } }