Android使用自定义布局制作进度圆

在values里创建attrs文件,然后在里面写圆的属性


<resources>
    <declare-styleable name="MyPb">
        <attr name="circle_color" format="color">attr>
        <attr name="circle_radius" format="dimension">attr>
        <attr name="circle_x" format="dimension">attr>
        <attr name="circle_y" format="dimension">attr>

    declare-styleable>
resources>

创建MyPb的class类继承View

public class MyPb extends View {
    private float cx;
    private float cy;
    private float radius;
    private Paint paint;
    private int sweepAngle;
    private int color;


    public MyPb(Context context) {
        this(context,null);
    }

    public MyPb(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取自定义属性
        TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.MyPb);
        //获取属性,后面的值是防止xml中没有定义而加的默认值
        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;
                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(15);
        canvas.drawText(progress+"%",cx-5,cy,paint);

    }
}

然后写布局

<com.bawei.moni.MyPb
        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"/>

你可能感兴趣的:(Android使用自定义布局制作进度圆)