Android自定义圆形进度条

来源:互联网 发布:mac系统字体库 编辑:程序博客网 时间:2024/06/05 00:31

布局

    <com.myapplication.Run        android:layout_width="wrap_content"        android:layout_height="wrap_content"        app:circle_color="#0000ff"        app:circle_radius="70dp"        app:circle_x="200dp"        app:circle_y="200dp" />

代码

public class Run extends View{    private float cx;    private float cy;    private float radius;    private Paint paint;    private int sweepAngle;    private int color;    public Run(Context context) {        this(context, null);    }    public Run(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        //获取自定义的属性        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyPb);        //获取颜色        color = a.getColor(R.styleable.MyPb_circle_color, Color.BLACK);        radius = a.getDimension(R.styleable.MyPb_circle_radius, 20);        cx = a.getDimension(R.styleable.MyPb_circle_x, 100);        cy = a.getDimension(R.styleable.MyPb_circle_y, 100);        //需要回收        a.recycle();        paint = new Paint();        paint.setAntiAlias(true);        paint.setStyle(Paint.Style.STROKE);        Timer timer = new Timer();        timer.schedule(new TimerTask() {                           @Override                           public void run() {                               if (sweepAngle > 360) {                                   return;                               }                               sweepAngle += 1;                               //刷新View                               //这个方法只能在主线程刷新UI//                        invalidate();                               //这个方法,也是刷新UI,并且可以在子线程刷新                               postInvalidate();                           }                       }                , 1000, 20);    }    @Override    protected void onDraw(Canvas canvas) {        paint.setColor(color);        paint.setStrokeWidth(5);        canvas.drawCircle(cx, cy, radius, paint);        paint.setColor(Color.RED);        RectF rectF = new RectF(cx - radius, cy - radius, cx + radius, cy + radius);        canvas.drawArc(rectF, -90, sweepAngle, false, paint);        //绘制文字        int progress = (int) (sweepAngle / 360f * 100);        paint.setStrokeWidth(0);        paint.setColor(Color.BLACK);        paint.setTextSize(35);        canvas.drawText(progress + "%", cx - 5, cy, paint);    }}
原创粉丝点击