public class CircleProgres extends View { Paint mPaint;//画笔 int radioWidth =30;//文字的长度 int progress=0;//中间的百分比从0开始 int max = 360; //所化的圆旋转360° public CircleProgres(Context context) { super(context); } public CircleProgres(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); new Thread(new Runnable() { @Override public void run() { while (true){ if (progress>360){ return; } //在子线程刷新数据 postInvalidate(); try { Thread.sleep(100);//线程睡眠 } catch (InterruptedException e) { e.printStackTrace(); } progress+=2;//中间的百分比每次加二 } } }).start();//开启线程 } public CircleProgres(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = getWidth()/2;//获取中心的宽度 int radius = center - radioWidth;//用圆的半径减去文字的长度从而让文字居中 mPaint.setColor(Color.BLUE);//设置圆的背景颜色 mPaint.setAntiAlias(true);//抗锯齿 mPaint.setStyle(Paint.Style.FILL_AND_STROKE);//这是颜色的格式,填充和边框 //drawCircle 画圆 canvas.drawCircle(center,center,radius,mPaint);//画圆 mPaint.setStrokeWidth(8);//这是边框的粗细 mPaint.setColor(Color.GRAY);//边框的颜色 mPaint.setStyle(Paint.Style.STROKE);//用来设置是空心还是实心 //center-radius用圆宽的中心点减去文字一半的长度 //enter+radius用圆宽的中心点加上文字一半的长度 //drawArc 画弧 RectF rectF = new RectF(center-radius,center-radius,center+radius,center+radius); canvas.drawArc(rectF,-90,progress,false,mPaint);//画圆的边框 mPaint.setColor(Color.BLACK);//文字的颜色 mPaint.setStyle(Paint.Style.FILL);//文字的粗细 int percent = progress; float textWidth = mPaint.measureText(percent+"%");//文字最后变成百分比 mPaint.setTextSize(20);//文字大小 //输出文字 canvas画布 canvas.drawText((float)progress/(float)360*100+ "%",center-radioWidth,center,mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } }
布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.circleprogeress.MainActivity"> <com.example.circleprogeress.CircleProgres android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>温馨提示:布局是主布局的主Activity什么都不用写,只要在创建一个Activity名字随意,用自己创建的Activity来关联主布局。