我正在开发一款关于android的小型测试游戏。我使用SurfaceView在Canvas上绘图。
我的问题出现了:只显示了一个框架,但listener.draw(..)
会被调用,所以我的游戏是静止图像。
线程每次迭代都会调用draw(..)
,但屏幕不会更新。
public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback {
// ...
@Override
protected void onDraw(Canvas canvas) {
if(alive) { // to prevent drawing if view exists but surface isn't created
// ...
final int savedState = canvas.save();
try {
canvas.clipRect(leftPadding, topPadding, leftPadding + finalWidth, topPadding + finalHeight);
canvas.translate(leftPadding, topPadding);
canvas.scale(scaleFactor, scaleFactor);
if(listener != null)
listener.draw(this, canvas);
} finally {
canvas.restoreToCount(savedState);
}
}
}
// ...
@Override
public void run() {
alive = true;
while(alive) {
if(!holder.getSurface().isValid())
continue;
long currentFrameStart = System.currentTimeMillis();
deltaFrameTime = currentFrameStart - lastFrameStart;
lastFrameStart = currentFrameStart;
listener.update(this, deltaFrameTime);
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
synchronized(holder) {
draw(canvas);
}
} finally {
if(canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
try {
Thread.sleep(10);
} catch(InterruptedException e) {
// ...
}
}
}
// ...
}
答案 0 :(得分:3)
http://danielnadeau.blogspot.de/2012/01/android-canvas-beginners-tutorial.html
而不是
try {
canvas = holder.lockCanvas();
synchronized(holder) {
draw(canvas);
}
} finally {
if(canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
我现在用
try {
canvas = holder.lockCanvas();
synchronized(holder) {
postInvalidate();
}
} finally {
if(canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
答案 1 :(得分:0)