![](/img/trans.png)
[英]SurfaceView How to setup android to only refresh the screen when it needs to be called?
[英]Is there an easy way to set up Android to only update screen when it needs to?
我正在制作棋盤游戲。 電路板永遠不會移動,但它上面的碎片有時會取決於用戶的互動。 還有一些UI元素可能會定期更新。
現在我設置的方式是覆蓋SurfaceView
子類的onDraw()
方法。 我有一個繪圖線程,在while循環中不斷調用postInvalidate()
:
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只在更改時更新?
你有正確的想法,但它需要一些改進。
你絕對不想像CPU那樣快速地循環。 你應該在每個循環中暫停你的線程一段時間。 你肯定不需要每毫秒都在你的循環中做所有事情。
我發現這個FPS控制指南在設計游戲循環時非常有幫助。
這個特定於Android的游戲循環指南還提供了許多很棒的示例代碼和深入的解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.