高效的android渲染
我读过很多关于 Android 游戏编程的教程, 它们都提供了与绘制游戏基本相同的解决方案,即有一个像这样旋转的专用线程:
public void run() {
while(true) {
if(!surfaceHolder.getSurface().isValid()) continue;
Canvas canvas = surfaceHolder.lockCanvas();
drawGame(canvas); /* do actual drawing here */
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
现在我想知道,这不是浪费吗?假设我有一个图形非常简单的游戏,因此绘制游戏的实际时间很少; 然后我将不断地绘制相同的东西,从其他线程窃取CPU; 如果游戏状态没有改变,可能会跳过绘图并睡一会儿, 我可以通过让状态更新线程维护合适的状态标志来检查。 但也许还有其他选择。例如,是否可以与渲染同步, 这样我就不会太频繁地发布更新?或者我错过了什么,而这正是 lockCanvas 所做的, 那是不是在适当的时间之前它会阻塞并燃烧CPU?
预先感谢
L。
I've read quite a few tutorials on game programming on android,
and all of them provide basically the same solution as to drawing the game, that is having a dedicated thread spinning like this:
public void run() {
while(true) {
if(!surfaceHolder.getSurface().isValid()) continue;
Canvas canvas = surfaceHolder.lockCanvas();
drawGame(canvas); /* do actual drawing here */
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
now I'm wondering, isn't this wasteful? Suppose I've a game with very simple graphics, so that the actual time in drawGame is little;
then I'm going to draw the same things on and on, stealing cpu from the other threads;
a possibility could be skipping the drawing and sleeping a bit if the game state hasn't changed,
which I could check by having the state update thread mantaining a suitable status flag.
But maybe there are other options. For example, couldn'it be possible to synchronize with rendering,
so that I don't post updates too often? Or am I missing something and that is precisely what lockCanvas does,
that is it blocks and burns no cpu until proper time?
Thanks in advance
L.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说你看到的教程是错误的,你真的想在主循环中等待。下例中的目标帧时间为 16 毫秒
I would say the tutorials you have seen are wrong, you really want to wait in the main loop. 16 milliseconds would be the target frame time in the example below
您不需要从线程中的循环中绘制画布,您可以根据请求执行此操作,例如在屏幕上移动手指时。
如果动画不密集,则可以仅使用自定义视图,然后通过某些用户输入事件使视图无效。
还可以停止线程,然后在同一个 SurfaceView 类中根据需要多次创建并重新启动它。
You don't need to draw canvas from a loop in a thread, you can do this on request, like when moving the finger over the screen.
If the animation is not intensive, one can use just a custom view and then invalidate() the view from some user input event.
It is also possible to stop the thread and then create and start it again, as many time as needed witin the same SurfaceView class.