2012-03-23 40 views
0

我的surfaceview onDraw方法有時會跳過在屏幕上繪製一些位圖,一旦它跳過,它再也不會繪製特定的位圖。 我的代碼SurfaceView onDraw跳過繪圖

public class Board extends SurfaceView implements SurfaceHolder.Callback{ 
//varaibles declared here 
public Board(){ 
    //initaializations here 
    getHolder().addCallback(this); 
} 
//my onDraw method 
protected void onDraw(Canvas canvas){ 
    for(int u = 0;u<6; u++){ 
     ai.get(u).draw(canvas);//each of these objects draws something on the screen. 
     human.get(u).draw(canvas); 
    } 
    postInvalidate(); 
} 

public void surfaceCreated(SurfaceHolder holder){ 
gameLoop = new GameLoop(this); 
gameLoop.start(); 
} 

的的onDraw()方法被調用在運行遊戲循環線程每100毫秒。

public class GameLoop extends Thread{ 
    Board board; 
    private final int DELAY = 100; 
    public GameLoop(Board board){ 
     this.board=board; 
    } 

    protected void run(){ 
    long beforeTime,timediff,sleep; 
    beforeTime = System.currentTimeMillis(); 
    while(running) 
    { 
     Canvas c = null; 
     try{ 
      c=board.getHolder.lockCanvas(); 
      synchronized(board.getHolder()){ 
       board.onDraw(c); 
      }finally{ 
      if(c!=null) 
      board.getHolder.unlockCanvas(c); 
      } 
     timeDiff = System.currentTimeMillis - beforeTime; 
     sleep = DELAY - timeDiff; 
     if(sleep<0) 
     sleep = 10; 
     try{ 
     Thread.sleep(sleep); 
     }catch(InterruptedException e){} 
     beforeTime = System.currentTimeMillis(); 
    } 
} 

所以這跳過發生這樣的:有時(在的onDraw()方法)當U = 0不汲取或u = 5時,它可以是U =任何可能的值,其餘的平一旦跳過該值,每次調用onDraw方法時都會跳過它。我希望我能夠說清楚。 我希望能幫助解決這個問題。謝謝

回答

0

因爲你正在從另一個線程更新你的主UI線程。 Android文檔表明,這會導致您遇到的不可預知的行爲。

考慮子類化AsyncTask來爲你做線程。有一些例程用於執行後臺工作並從UI線程本身發佈到主UI線程。

基本上,你調用任務的執行,然後調用它的doInBackground例程,當它完成時,它調用onPostExecute例程和任務的結果。

這些源應該是幫助理解問題和子類的AsyncTask有用: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html http://developer.android.com/reference/android/os/AsyncTask.html

+0

由於凸輪。我通過在gameLoop線程postInvalidating修復它,而不是在onDraw方法,它迄今爲止工作正常。 – Evans 2012-04-10 12:41:07