我正在做一个棋盘游戏。板子永远不会移动,但它上面的部分有时会根据用户交互而移动。还有一些 UI 元素可能会定期更新。
现在我设置它的方式是覆盖子类的onDraw()
方法SurfaceView
。postInvalidate()
我有一个在while循环中不断调用的绘图线程:
class PanelThread extends Thread
{
//...
long sleepTime = 0;
long nextGameTick = System.currentTimeMillis();
@Override
public void run()
{
Canvas c;
while (_run)
{ // When setRunning(false) occurs, _run is
c = null; // set to false and loop ends, stopping thread
try
{
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder)
{
// Insert methods to modify positions of items in onDraw()
_panel.postInvalidate();
}
} finally
{
if (c != null)
{
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
nextGameTick += MILLISECONDS_PER_FRAME;
sleepTime = nextGameTick - System.currentTimeMillis();
if(sleepTime >= 0)
{
try
{
sleep(sleepTime, 0);
} catch (InterruptedException e)
{
continue;
}
}
else
{
//we're behind, oh well.
System.out.println("behind!");
nextGameTick = System.currentTimeMillis();
}
}
}
这效率不高,并且占用大量 CPU。有没有一种简单的方法可以让 android 仅在发生变化时才更新?