如何创建CanvasView对象

时间:2018-01-14 20:04:23

标签: java android canvas

我有一个类CanvasView:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import java.util.Random;




public class CanvasView extends View {


    private Canvas canvas;
    private Paint paint;
    private int width;
    private int height;
    Random random = new Random();


    public CanvasView(Context context,AttributeSet attrs) {
        super(context);
        super.onDraw(canvas);
        initPaint();    //here i just create my Paint      
    }

    @Override
    public void onDraw(Canvas canvas) {
        this.canvas = canvas;
    }



    public void drawRandom() {
        canvas.drawCircle(random.nextInt(700), random.nextInt(700), random.nextInt(200), paint);

    }
}

然后我尝试在另一个活动中创建CanvasView对象:

 canvasView = new CanvasView(this,null);

然后我尝试调用方法drawRandom()

  canvasView.drawRandom();

然后发生错误:Attempt to invoke virtual method 'void android.graphics.Canvas.drawCircle(float, float, float, android.graphics.Paint)' on a null object reference

我知道这意味着此时canvas = null但是如何修复它?我尝试了很多但仍然无法做到。

如果这个问题和我一样愚蠢,请不要责怪我,我是初学者,对不起。

1 个答案:

答案 0 :(得分:0)

public CanvasView(Context context, AttributeSet attrs) {
        super(context);
        initPaint();    //here i just create my Paint
    }

    @Override
    public void onDraw(Canvas canvas) {
        this.canvas = canvas;
        canvas.drawCircle(random.nextInt(700), random.nextInt(700), random.nextInt(200), paint);
    }

    public void drawRandom() {
        invalidate();
    }

顺便说一下,不要忘记在New CanvasView()之后将它添加到窗口。 像这样:

ViewGroup viewGroup =(ViewGroup) ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
        viewGroup.addView(canvasView);