触摸显示屏时更改onDraw位图

时间:2013-02-15 14:16:08

标签: android bitmap ontouchevent ondraw

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

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

1 个答案:

答案 0 :(得分:0)

对于throwIfRecycled错误this is a possible solution

但是,就像Gabe说的那样,你应该在创建应用程序时解码一次Bitmap,然后在需要时绘制它。