0

我写了一个游戏,我试图让它变得更好并消除错误,我的菜单和游戏状态本身都依赖于一个线程,但是对于菜单我锁定了绘图,以便它只绘制每个屏幕一次. 我的手机在菜单上过热,所以我只想在游戏状态下创建线程,并使菜单独立于线程,例如在触摸时重绘。

我知道如何做所有这些,而且它非常简单,但是我遇到了奇怪的错误,我的位图的空指针异常在线程打开时可以完美地工作。

我有一个 onDraw(Canvas c) 函数,我已经在其中编写了在每个状态(如菜单或游戏状态)上绘制的内容

在线程中它看起来像这样(只是绘图部分)

    c = null;
    c = holder.lockCanvas();
    synchronized(holder){
    onDraw(c);
    }
    holder.unlockCanvasAndPost(c);

现在我写了一个简单的方法来调用以便在菜单中绘制

private void reDraw(){
menuCanvas = null;
menuCanvas = holder.lockCanvas();
synchronized(holder){
onDraw(menuCanvas);}
holder.unlockCanvasAndPost(menuCanvas);
}

而在 onSizeChanged 方法中 @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { screenW = w; 屏幕H = h;

BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
while (bmpBackground==null){
if (screenW>500){
bmploader = BitmapFactory.decodeResource(getResources(),R.drawable.bg_planet,options);
bmpBackground = Bitmap.createScaledBitmap(bmploader, screenW, screenW, true);
if (bmploader!=null){
bmploader.recycle();
bmploader = null;
}
}
else{
bmploader =     BitmapFactory.decodeResource(getResources(),R.drawable.bg_planet_small,options);
            bmpBackground = Bitmap.createScaledBitmap(bmploader, screenW, screenW, true);
            if (bmploader!=null){
                bmploader.recycle();
                bmploader = null;
            }
        }
        }
        loadMusic();
        loadBitmaps();
        loadShip();
        changeState(states.TITLE);
        reDraw();
        super.onSizeChanged(w, h, oldw, oldh);
    }

它几乎告诉我 bmpBackground 为空并引发错误。在我刚刚更改为标题状态并且它正在正常绘制之前(使用线程绘图);

4

1 回答 1

0

Sometimes/often, onSizeChanged gets called a number of times in succession, the first time with a width and height of w=0 and h=0.

The best thing to do is

a) add a check to see if width=0 and if so do nothing (it'll call this again with the proper dimensions; you also don't need to add a check for height=0, because either w and h will be 0 or they will be >0 and your call to bitmap creation will run without an error)

b)override the onSurfaceChanged of your surfaceview instead of onSizeChanged and do the recalculation/creation of your bitmaps then.

于 2014-03-09T19:48:12.367 回答