2013-02-15 47 views
0

我对我的代码有疑问。每次有人触摸显示器时,我都希望更改位图。触摸显示屏时更改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 
+0

如果发生崩溃,请发布logcat。此外,在每次触摸时解码位图会非常昂贵,因此最好在开始时解码一次,并将其设置为预解码的位图。 – 2013-02-15 14:19:52

回答

0

对于throwIfRecycled错误,this is a possible solution

但是,就像Gabe所说的,你应该在你的应用程序创建时解码你的Bitmap,然后在你想要的时候绘制它。