我编了一个线程的表面视图。它可以工作,但似乎不能很好地刷新。我所说的不刷新是指:如果我移动一个位图位置,它将继续在最后的位置+新的位置绘制。
这是我的代码。
public GameView(Context context)
{
super(context);
holder=getHolder();
currentScreen=new TestScreen();
currentScreen.Load(this.getResources());
}
protected void Resume()
{
isRunning=true;
renderThread=new Thread(this);
renderThread.start();
}
public void run()
{
while(isRunning)
{
gametime=lasttime-System.nanoTime();
lasttime=System.nanoTime();
if(!holder.getSurface().isValid())
continue;
if(!(currentScreen==null))
{
currentScreen.Update(gametime);
Canvas cv=holder.lockCanvas();
currentScreen.Draw(cv, gametime);
holder.unlockCanvasAndPost(cv);
}
}
}
public void pause()
{
isRunning=false;
while(true)
{
try
{
renderThread.join();
}
catch (InterruptedException e)
{
}
break;
}
renderThread=null;
}
屏幕类的代码
public void Load(Resources resources) {
square=BitmapFactory.decodeResource(resources, R.drawable.square);
x=y=0;
super.Load(resources);
}
@Override
public void Update(long gametime) {
x++;
super.Update(gametime);
}
@Override
public void Draw(Canvas cv, long gametime) {
cv.drawBitmap(square, x, y, null);
super.Draw(cv, gametime);
}
我试过不使用Screen类的方法,但也是一样的。我是不是少了一些清除屏幕的线条?
由于你没有向lockCanvas()提供一个肮脏的矩形,系统将不保证在unlockCanvasAndPost(Canvas)和下次调用lockCanvas()之间Canvas会发生什么。
因此,你必须重新绘制Canvas的全部内容,而不仅仅是已经改变的部分。看起来你只绘制了正在移动的方块,而没有绘制背景来填充Canvas的其余部分。
注意:如果你使用lockCanvas(Rect dirty),情况会有所不同。