用SurfaceView写一个自制的背景图,并且可以移动,加上安卓飞机大战(一)中的BackgroundManager类,可以直接使用



GameView代码:


public class GameView extends SurfaceView implements SurfaceHolder.Callback,Runnable{
private SurfaceHolder hd=null;
private Canvas canvas=null;
private BackgroundManager backgroundmanager;


public GameView(Context context) {
super(context);
this.setFocusable(true);
hd=this.getHolder();
hd.addCallback(this);
}

public void run() {
while(isrunning){
mydraw();
try {
Thread.sleep(100);//每100s刷新一次屏幕
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public void mydraw(){
try{
if(hd!=null){
canvas=hd.lockCanvas();
canvas.drawColor(Color.BLUE);
backgroundmanager.drawbackground(canvas);
}catch(Exception e){
e.printStackTrace();
}finally{
if(canvas!=null)
hd.unlockCanvasAndPost(canvas);
}
}

public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

}


public void surfaceCreated(SurfaceHolder arg0) {
thread=new Thread(this);//定义一个新线程
thread.start();
backgroundmanager=new BackgroundManager(this);
}

@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}




MainActivity 代码:


public class MainActivity extends Activity {

private GameView gameview=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameview=new GameView(this);
setContentView(gameview);
}



这样就能实现背景的循环移动了,layout中的xml文件直接不用管。