我有一个扩展 View 的类。这个类有成员变量mCanvas
private Canvas mCanvas;
该变量是在调整视图大小时创建的,因此设置了画布的适当大小:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int curW = mBitmap != null ? mBitmap.getWidth() : 0;
int curH = mBitmap != null ? mBitmap.getHeight() : 0;
if (curW >= w && curH >= h) {
return;
}
if (curW < w) curW = w;
if (curH < h) curH = h;
Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(canvasBitmap);
if (mBitmap != null) {
mCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = canvasBitmap;
}
但在我的 onDraw 函数中,当我尝试获取画布的宽度/高度时,出现空指针异常。我不确定 onSizeChanged 何时实际被调用,我假设它总是在创建视图时被调用,因此在 onDraw 之前被调用。
但如果我的 onDraw 以此开头:
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
if(mCanvas == null)
{
Log.d("testing","mCanvas is null"
}
当我到达 onDraw 时,logCat 总是显示消息“mCanvas 为空”。
所以我更改了代码,以便当我读取 onDraw 时 mCanvas 为空,我只需再次创建它:
private void resizeCanvas()
{
int curW = mBitmap != null ? mBitmap.getWidth() : 0;
int curH = mBitmap != null ? mBitmap.getHeight() : 0;
if (curW >= this.getWidth() && curH >= this.getHeight()) {
return;
}
if (curW < this.getWidth()) curW = this.getWidth();
if (curH < this.getHeight()) curH = this.getHeight();
Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(canvasBitmap);
if (mBitmap != null) {
mCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = canvasBitmap;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
if(mCanvas == null)
{
resizeCanvas();
if(mCanvas == null)
{
Log.d("test","canvas is still null");
}
logCat 仍然打印“canvas is still null”
有人能解释一下这里发生了什么吗?我对 android 很陌生,大部分代码都来自我一直在玩的 touchpaint 示例。
如果我检查 resizeCanvas 函数内部 mCanvas 是否为空,它总是说它不为空。但如果我在调用该函数后立即检查它总是为空。