Android自定义view圆形进度条

来源:互联网 发布:北大燕京学堂知乎 编辑:程序博客网 时间:2024/04/30 20:00
package ztz.com.customview.view;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Rect;import android.graphics.RectF;import android.util.AttributeSet;import android.view.View;/** * 自定义视图_进度条 */public class CustomProgressView extends View {    //定义一个画笔    private Paint mpaint;    private int progress = 0;    private Rect textrect;    public CustomProgressView(Context context, AttributeSet attrs) {        super(context, attrs);        //创建一个画笔        mpaint = new Paint();        //设置抗锯齿        mpaint.setAntiAlias(true);        //画笔的颜色        mpaint.setColor(Color.BLUE);        //是否填充画笔        mpaint.setStyle(Paint.Style.STROKE);        //在线程中更新onDraw方法        new Thread(){            @Override            public void run() {                super.run();                while (true){                    if(progress>=360){                       return;                    }                    postInvalidate();                    progress+=10;                    try {                        sleep(100);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }        }.start();    }    public CustomProgressView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public CustomProgressView(Context context) {        super(context);    }    //重写ondraw方法    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //获取当前view的宽度        int x = getWidth() / 2;        int y = getHeight() / 2;        //半径        int radius = 200;        //设置画笔的粗细        mpaint.setStrokeWidth(30);        //定义view的区域        RectF rectF = new RectF(x-radius, y-radius, x+radius, y+radius);        //画弧        canvas.drawArc(rectF,-90,progress,false,mpaint);        int text = (int)((float)progress / 360 * 100);        //字体的粗细        mpaint.setStrokeWidth(2);        //获取字符串的宽度        int textWidth = (int) mpaint.measureText(text+"%");        //获取字符串的高度        textrect = new Rect();        //字号的大小        mpaint.setTextSize(30);        mpaint.getTextBounds(text+"%",0,(text+"%").length(), textrect);        //画文字        canvas.drawText(text+"%",x-textWidth/2,y+textrect.height() /2,mpaint);    }}
原创粉丝点击