新建MyView类,继承View。添加两个参数的构造方法,并覆写onDraw()方法 new一个Paint 画笔对象。在onDraw()方法中画图。paint是画笔,canvas是画布。
package com.engineer.shizhibin.drawpicture;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
/**
* 1.覆写onDraw()
* 2.初始化画笔
* 3.canvas 画板
* Created by 13922 on 2018/6/2.
*/
public class MyView extends View {
private Paint mPaint = new Paint();
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(100,100,300,100,mPaint);
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(20);
canvas.drawCircle(290,250,180,mPaint);
mPaint.setColor(Color.YELLOW);
canvas.drawCircle(480,430,180,mPaint);
mPaint.setColor(Color.BLACK);
canvas.drawCircle(670,250,180,mPaint);
mPaint.setColor(Color.GREEN);
canvas.drawCircle(860,430,180,mPaint);
mPaint.setColor(Color.RED);
canvas.drawCircle(1050,250,180,mPaint);
mPaint.setTextSize(100);
canvas.drawText("北京欢迎你",600,1000,mPaint);
}
}
在Activity_Main.xml中添加刚才自定义的View,设置属性。一定要用类全名。
<com.engineer.shizhibin.drawpicture.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0ff" />
画图结果: