0

我对我的代码有疑问。我希望每次有人触摸显示器时我的位图都会改变。

protected boolean processTouch(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        player.setGraphic(BitmapFactory.decodeResource(Game.res, R.drawable.sprite2));

    } 
    return true;
}

在我的 player.java 文件中,我输入:

public class Player extends Sprite
{
public Player(int x, int y)
{
    super(BitmapFactory.decodeResource(Game.res, R.drawable.sprite1), x-350, y, 50, 17, 5, 2);

}
public void update()
{
getGraphic();
}

public Bitmap getGraphic() 
{
    return bitmap;
}
public void setGraphic(Bitmap bitmap)
{
    this.bitmap = bitmap;
}


private Bitmap bitmap;}

我的 Sprite 类包含:

 public Sprite(Bitmap bitmap, int x, int y, int width, int height, int fps, int frameCount) 
{
    this.bitmap = bitmap;

}
public Bitmap getGraphic() 
{
    return bitmap;
}
private Bitmap bitmap;

然后我想显示它:

canvas.drawBitmap(s.getGraphic(), s.getSourceRect(), destRect, null);

但是,当我尝试启动游戏时,它崩溃了。我怎么解决这个问题?

编辑

日志:

02-15 15:29:51.174: I/ActivityManager(18563): Displayed com.example.nic_beta/.Game: +488ms
02-15 15:29:51.197: W/dalvikvm(29635): threadid=11: thread exiting with uncaught exception (group=0x419cb930)
02-15 15:29:51.197: E/AndroidRuntime(29635): FATAL EXCEPTION: Thread-23004
02-15 15:29:51.197: E/AndroidRuntime(29635): java.lang.NullPointerException
02-15 15:29:51.197: E/AndroidRuntime(29635):    at android.graphics.Canvas.throwIfRecycled(Canvas.java:1025)
02-15 15:29:51.197: E/AndroidRuntime(29635):    at android.graphics.Canvas.drawBitmap(Canvas.java:1127)
02-15 15:29:51.197: E/AndroidRuntime(29635):    at com.example.nic_beta.Panel.onDraw(Panel.java:70)
02-15 15:29:51.197: E/AndroidRuntime(29635):    at com.example.nic_beta.RunnerThread.run(Panel.java:187)
02-15 15:29:51.213: W/ActivityManager(18563):   Force finishing activity com.example.nic_beta/.Game
02-15 15:29:51.260: W/ActivityManager(18563):   Force finishing activity com.example.nic_beta/.Menu
4

1 回答 1

0

对于 throwIfRecycled 错误,这是一个可能的解决方案

但是,就像 Gabe 所说,您应该在创建应用程序时对 Bitmap 进行一次解码,然后在需要时绘制它。

于 2013-02-15T15:57:48.830 回答