I am calling Draw function as follows.Basically i want to display bouncing ball in surface holder. For this i am writing the code as follows:
private void getDrawing() {
for (i = 0; i < 1000; i++) {
if ((i + 1 % 20) == 0) {
Rect r = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawRect(r, paint);
}
canvas = mSurfaceHolder.lockCanvas();
Draw(canvas);
}
}
@post(new Runnable() {
public void run() {
this.invalidate();
}
});
protected void Draw(Canvas c) {
ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
if (x < 0 && y < 0) {
x = 1000 / 2;
y = 1000 / 2;
} else {
x += xVelocity;
y += yVelocity;
if ((x > 1000 - ball.getWidth()) || (x < 0)) {
xVelocity = xVelocity * -1;
}
if ((y > 1000 - ball.getHeight()) || (y < 0)) {
yVelocity = yVelocity * -1;
}
}
c.drawBitmap(ball, x, y, null);
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
Problem is the canvas is not getting invalidating and the succesive draw calls are superimposing.How to erase the canvas after each draw as happens in the case of invalidate function.I am also writing the following code but its also not helping :
Rect r = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawRect(r, paint);
Is there any other approach to display bouncing ball on surface holder.How can we use OnDraw and Invalidate functions on surfaceholder if we don't extend from View class.
Regards,