【问题标题】:SurfaceView onDraw skips drawingSurfaceView onDraw 跳过绘图
【发布时间】:2012-03-23 17:02:34
【问题描述】:

我的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 方法时它都会跳过它的值。我希望我能够说得足够清楚。 我很感激帮助解决这个问题。谢谢

【问题讨论】:

    标签: android surfaceview ondraw


    【解决方案1】:

    按原样,您正在从另一个线程更新您的主 UI 线程。 Android 文档表明这会导致您遇到的不可预知的行为。

    考虑子类化 AsyncTask 来为您处理线程。有一些例程用于执行后台工作并从 UI 线程本身发布到主 UI 线程。

    基本上,您在任务上调用 execute,然后调用它的 doInBackground 例程,完成后,它调用 onPostExecute 例程以及任务的结果。

    这些来源应该有助于理解问题和子类 AsyncTask: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html http://developer.android.com/reference/android/os/AsyncTask.html

    【讨论】:

    • 谢谢卡姆。我通过在 gameLoop 线程中而不是在 onDraw 方法中的 postInvalidating 来修复它,到目前为止它工作正常。
    猜你喜欢
    • 2011-09-19
    • 2011-09-09
    • 2011-08-04
    • 2013-03-11
    • 2011-09-07
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多