在线程和绘图方法之间传递Canvas无法正常工作

时间:2018-10-21 17:29:40

标签: android android-animation

我想使用SurfaceView创建简单的蛇游戏,而我正在使用本示例How can I use the animation framework inside the canvas?的线程,但是在调用update()之后看不到任何更改,我认为我可能在错误的画布上工作,但是我不知道为什么。

GameView:

public class GameView extends SurfaceView implements SurfaceHolder.Callback {

   private int mScreenHeight;
   private int mScreenwidth;
   private GameThread gameThread;
   private Paint mPaint;
   private final int SQUARES_ON_BOARD = 512; // number of squares on board
   private final int SQUARE_SIDE;

   public GameView(Context context, int mScreenHeight, int mScreenWidth) {
       super(context);
       mPaint = new Paint();
       mPaint.setColor(Color.WHITE);
       this.mScreenHeight = mScreenHeight;
       this.mScreenwidth = mScreenWidth;

       // creating variables to calculate snake position etc not important in this question 

       getHolder().addCallback(this);
       setFocusable(true);
   }


    public void update(Canvas canvas) {
       canvas.drawColor(Color.WHITE); // create background
       mPaint.setColor(Color.BLACK);
       for(int i = size; i > 0; --i){
           int left = snakeTailX + i*SQUARE_SIDE;
           int top = snakeTailY;
           int right = left + SQUARE_SIDE;
           int bottom = top + SQUARE_SIDE;
           canvas.drawRect(left, top ,right, bottom , mPaint);
       }
       invalidate();
       snakeTailX++;
   }
   @Override
   public void surfaceCreated(SurfaceHolder surfaceHolder) {
       gameThread = new GameThread(getHolder(), this);
       gameThread.setRun(true);
       gameThread.run();
   }
}

GameThread:

public class GameThread extends Thread {
   private SurfaceHolder mSurfaceHolder;
   private GameView mGameView;
   private boolean run = false;

   public GameThread(SurfaceHolder mSurfaceHolder, GameView mGameView) {
       this.mSurfaceHolder = mSurfaceHolder;
       this.mGameView = mGameView;
   }

   public void setRun(boolean run) {
       this.run = run;
   }

   @Override
   public void run() {
       Canvas canvas;
       while (run) {
           try {
               sleep(1000);
               canvas = mSurfaceHolder.lockCanvas();
               try {
                   synchronized (mSurfaceHolder) {
                       mGameView.update(canvas);
                   }
               } finally {
                   if (canvas != null) {
                       mSurfaceHolder.unlockCanvasAndPost(canvas);
                   } 
               }
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
   }
}

0 个答案:

没有答案