Reputation: 13
I recently started to learn about android and java and to practice I started to make a space invader-type game.
In order to draw all the images(player/enemy/etc) I've been using an overridden onDraw
method and canvas.DrawBitmap(..)
. This is where my problem starts. Whenever I draw the images with their new X,Y coordinates, the previous bitmap is still on the canvas which makes everything overlap. Is there some way to refresh the canvas or just get rid of the "leftovers"(I don't even know what to call them). When I made this I was under the impression that I just move the 1 image across the screen but it looks like I was wrong.
This is the code I use to draw the player bitmap:
public void render(Canvas canvas){
//draw the player image
canvas.drawBitmap(_bmPlayerImg, (float) (_dX - (_iHalfWidth)),
(float)(_dY - (_iHalfHeight)), null);
}
The onDraw()
method:
@Override
protected void onDraw(Canvas canvas) {
//draw the player
_player.render(canvas);
}//end method
The onDraw()
method is called in a thread I use as my game timer every 50ms:
public Runnable runnable = new Runnable() {
@Override
public void run() {
canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
synchronized(surfaceHolder){
//update the state of all objects in the game
gamePanel.update(canvas);
gamePanel.onDraw(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}//end if
}//end finally
handler.postDelayed(this, _iRepeatTime);
}
};
Any help is appreciated...I tried looking it up but I couldn't find anything.
Upvotes: 0
Views: 598
Reputation: 1237
Before you draw anything on the canvas:
//clear the canvas
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
And now your canvas is clear and you can draw your character.
If your onDraw method was in an expanded view class and was triggered by you calling invalidate(), then the canvas would automatically clear itself. But you are manually calling it (looks like you are using a surface/texture view?), so you have to clear it manually.
Upvotes: 1