我的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 :(得分:0)
原样,您正在从另一个线程更新主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