自定义一个进度条+百分比

来源:互联网 发布:windows ant下载 编辑:程序博客网 时间:2024/06/06 02:18
 activity_xml界面
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    >    <com.bwei.test2.CustomProgressView        android:layout_width="match_parent"        android:layout_height="match_parent"        /></LinearLayout>
CustomProgressView页面
public class CustomProgressView extends View{ //定义一个画笔 private Paint paint; private boolean running = true;//一个变量 ,,控制循环的 private int progress = 0;//进度 一开始是0 public CustomProgressView(Context context) { super(context); } public CustomProgressView(Context context, AttributeSet attrs) { super(context, attrs); //创建一个画笔 paint = new Paint(); //抗锯齿 paint.setAntiAlias(true); //设置画笔的颜色 paint.setColor(Color.BLUE); //设置画笔 填充是空心的Paint.Style.STROKE paint.setStyle(Paint.Style.STROKE); //子线程刷新 postInvalidate new Thread(new Runnable() { @Override public void run() { //循环 while(running){ if(progress>=360){ //如果进度已经大于了360,就跳出 running = false; return; } progress+=10;//进度每次加10 //子线程刷新, postInvalidate(); try { //睡眠 Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } public CustomProgressView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //getWidth()获取当前View的宽度 int x = getWidth()/2;//在当前视图的中心x轴 int y = getHeight()/2;//在当前视图的中心y轴 //半径radius int radius = 200; //设置画笔的粗细 paint.setStrokeWidth(30); //定义一个区域,,弧形的范围,左上右下 RectF rectF = new RectF(x-radius,y-radius,x+radius,y+radius); //useCenter true从中心点开始 ,false中心点不显示 canvas.drawArc(rectF,-90,progress,false,paint); //计算百分比的值,float是避免出现0,计算出来再强转成int int zhi = (int) ((float)progress / 360 * 100); //measureText测量字符串的宽度,,竖着的 float zhiWidth = paint.measureText(zhi+"%"); //根据这个矩形 求 百分比值的高度 Rect rectZhi = new Rect(); //获取字符串的高度rectZhi.height() //第一个参数是 要求的字符串,,第二个参数是从哪里开始,第三个参数是到哪里结束,最后一个是矩形 paint.getTextBounds(zhi+"%",0,(zhi+"%").length(),rectZhi); paint.setTextSize(30);//设置画笔的大小 paint.setStrokeWidth(1);//字体大小 //画文字 canvas.drawText(zhi+"%",x-zhiWidth/2,y+zhiWidth/2,paint); }}