为什么 onDraw() 不能访问 myPaint?

Why can't onDraw() access myPaint?

我正在使用 CanvasPaint 创建一个简单的圆图。

我注意到当我在 init() 之外创建变量 myPaint 时,一切正常;由以下代码说明:

public class Drawing extends View {

    Paint myPaint;
    public Drawing(Context context) {
        super(context);
        init();
    }

    public void init(){
        myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        myPaint.setColor(Color.parseColor("yellow"));
    }


    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawCircle(getMeasuredWidth() /2, getMeasuredHeight() /2 , 100f, myPaint);
        super.onDraw(canvas);
    }
}

然而,当我做完全相同的事情时,而是在 init() 中创建 myPaint,我在 onDraw() 中收到 myPaint 的错误;由以下代码说明:

public class Drawing extends View {


public Drawing(Context context) {
    super(context);
    init();
}

public void init(){
    Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    myPaint.setColor(Color.parseColor("yellow"));
}


@Override
protected void onDraw(Canvas canvas) {

    canvas.drawCircle(getMeasuredWidth() /2, getMeasuredHeight() /2 , 100f, myPaint);
    super.onDraw(canvas);
}
}

为什么会这样?谢谢!

在代码 B 中,您定义了一个局部变量,该变量只能在定义它的代码块内访问(在本例中为 init 方法)。相反,代码 A 定义了一个 属性,它可以在您的对象内部访问,并与它并排离开。

你也可以看看this

Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.