新建一个类MyView,继承View,实现2个构造方法,重写onDraw()方法
### main布局, MainActivity里面不变动
<com.example.view.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" />
### MyView
public class MyView extends View { private static int WIDTH = 90; private Paint paint = new Paint(); private int delteX, delteY; private Rect rect = new Rect(0, 0, WIDTH, WIDTH); public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); paint.setColor(Color.GREEN); paint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawRect(rect, paint); paint.setColor(Color.RED); canvas.drawLine(0, 50, WIDTH, 50, paint); canvas.drawLine(0, 70, WIDTH, 70, paint); canvas.drawLine(0, 50, 0, 70, paint); canvas.drawLine(WIDTH, 50, WIDTH, 70, paint); paint.setColor(Color.DKGRAY); RectF rfs=new RectF(0,0,getMeasuredWidth(),getMeasuredHeight()); canvas.drawArc(rfs,-15,210,false,paint); paint.setColor(Color.YELLOW); canvas.drawCircle(0, 0, WIDTH / 2, paint); RectF ref=new RectF(0,0,getMeasuredWidth(),getMeasuredHeight()); canvas.drawArc(ref,0,180,false,paint); paint.setColor(Color.GREEN); RectF rec=new RectF(0,0,getMeasuredWidth(),getMeasuredHeight()); canvas.drawArc(rec,15,150,false,paint); paint.setColor(Color.RED); RectF rf=new RectF(0,0,getMeasuredWidth(),getMeasuredHeight()); canvas.drawArc(rf,30,120,false,paint); paint.setColor(Color.BLUE); // canvas.drawCircle(90,0,WIDTH/2,paint); RectF rectF = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight()); // int a = -45; // canvas.drawArc(rectF, a, (90 - a) * 2, false, paint); canvas.drawArc(rectF,45,90,false,paint); } }