Canves 基本操作 (屏幕上绘制网格和XY坐标)

文章目录

        • 1.canves的save和restore方法
        • 2.屏幕上绘制网格线和xy轴坐标

1.canves的save和restore方法

方法 含义
save() 保存画布之前的状态
restore() 将画布回复到之前的状态

可以理解为save方法是将之前canves的画布内容状态保存起来,然后对画布进行一些操作比如:平移、放缩、旋转、错切、裁剪等操作。restore将canves回复到save之前的状态,将save之后的操作内容合并。

 protected void onDraw(Canvas canvas) {
       super.onDraw(canvas);
//       save之前绘制一个矩形
       canvas.drawRect(0,0,100,100,paint);
        canvas.save();
        int hafWidth = getWidth() / 2;
        int hafHeight = getHeight() / 2;
//        save后画布平移
        canvas.translate(hafWidth,hafHeight);
//        平移后绘制(100,100,200,200)矩形
        canvas.drawRect(100,100,200,200,paint);
        canvas.drawText("Save后",150-textPaint.measureText("Save后")/2,150,textPaint);
        //回复到save之前的状态
        canvas.restore();
        //回复到save之前的状态后绘制和平移后一样坐标的矩阵(100,100,200,200)
        canvas.drawRect(100,100,200,200,paint);
    }

发现save后绘制的 canvas.drawRect(100,100,200,200,paint); 和restore()后绘制的canvas.drawRect(100,100,200,200,paint); 显示的位置不一样,这就是 canvas.save();canvas.restore();
Canves 基本操作 (屏幕上绘制网格和XY坐标)_第1张图片

2.屏幕上绘制网格线和xy轴坐标

使用canves的drawLine方法和drawText方法

public class MyTestView extends View {
    private Paint paint;
    private Picture mPicture=new Picture();
    private Paint xyPaint;
    //网格的宽度
    private  int gridWidth=50;
    private  Paint textPaint;
    public MyTestView(Context context) {
        this(context, null);
    }

    public MyTestView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyTestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
        recording();    // 调用录制
    }
    // 2.录制内容方法
    private void recording() {
        // 开始录制 (返回值Canvas)
        Canvas canvas = mPicture.beginRecording(500, 500);
        canvas.drawColor(Color.GREEN);
        canvas.drawCircle(100,100,100,paint);
        mPicture.endRecording();
    }

    private void initPaint() {

        paint = new Paint();
        //设置抗锯齿
        paint.setAntiAlias(true);
        //设置画笔的颜色
        paint.setColor(Color.parseColor("#C2C2C2"));
        //设置画笔的宽度
        paint.setStrokeWidth(2);
        xyPaint=new Paint();
        xyPaint.setStrokeWidth(4);
        xyPaint.setColor(Color.BLACK);

        textPaint=new Paint();
        textPaint.setTextSize(20);
        textPaint.setColor(Color.RED);

    }
    @SuppressLint("Range")
    @Override
    protected void onDraw(Canvas canvas) {
       super.onDraw(canvas);
        canvas.save();
        int hafWidth = getWidth() / 2;
        int hafHeight = getHeight() / 2;
        canvas.translate(hafWidth,hafHeight);
        int currentWidth=gridWidth;
        //绘制垂直竖线

        while (currentWidth

Canves 基本操作 (屏幕上绘制网格和XY坐标)_第2张图片

你可能感兴趣的:(Canves)