gpt4 book ai didi

android - SurfaceView 不会重新绘制

转载 作者:搜寻专家 更新时间:2023-11-01 08:54:03 25 4
gpt4 key购买 nike

我正在 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) {
// ...
}
}
}

// ...
}

最佳答案

谷歌搜索几个小时给了我一个解决方案:

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);
}
}

关于android - SurfaceView 不会重新绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com