我开始学习Android上的编程,但我遇到了Bitmap
工厂的问题。这是代码:
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {
private MainThread gameThread;
public ResourceManager resourceManager;
public MainGamePanel (Context context) {
super(context);
getHolder().addCallback(this);
try {
Bitmap temp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
} catch (NullPointerException e) {
Log.d(MainGamePanel.class.getSimpleName(), "Null Pointered!");
}
gameThread = new MainThread(getHolder(),this);
setFocusable(true);
}
如果我尝试在此处制作位图,BitmapFactory
会抛出NullPointerException
。
但是,当我稍后在onDraw()
函数中执行此操作时:
protected void onDraw(Canvas canvas)
{
//Add the drawing code here
Bitmap temp = BitmapFactory.decodeResource(getResources(), R.drawable.sprite);
canvas.drawBitmap(temp, 10, 10, null);
}
onDraw()
函数由另一个线程运行:
public class MainThread extends Thread {
private boolean running;
private SurfaceHolder surfaceHolder;
private MainGamePanel gamePanel;
public MainThread(SurfaceHolder _surfaceHolder, MainGamePanel _gamePanel)
{
surfaceHolder=_surfaceHolder;
gamePanel = _gamePanel;
}
public void run() {
Canvas canvas;
running = true;
while(running)
{
canvas = null;
try{
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder)
{
//WHY DOES THIS (The folllowing line) WORK!????
this.gamePanel.onDraw(canvas);
}
}
finally
{
if(canvas!=null)
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
所以我的问题是:BitmapFactory
为什么在onDraw()
下工作但在构造函数中不工作?
感谢任何回答我问题的人!