我正在调用Draw函数如下。基本上我想在表面支架中显示弹跳球。 为此,我正在编写如下代码:
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);
是否还有其他方法可以在表面支架上显示弹跳球。如果我们不从View类扩展,我们如何在surfaceholder上使用OnDraw和Invalidate函数。
此致
答案 0 :(得分:1)
您在后台线程中无效,而invalidate只能在主线程中运行。如果要连续使其无效,请写
invalidate();
在onDraw函数的末尾。