Android中的三种视图
view
SurfaceView
GlsurfaceView
1、surfaceview
具有双缓冲机制
容易使用多线程技术构造游戏的主循环
class Mysurface extends SurfaceView implements Callback{
private SurfaceHolder sfh;
private Paint paint;
private Canvas canvas;
private boolean runFlag;
private int x,y;
private int w,h;
public Mysurface(Context context){
super(context);
sfh=this.getHolder();
sfh.addCallback(this);//surfaceholder中添加callback
canvas=sfh.lockCanvas();//不仅获取canves 而且对获取的canves进行加锁
paint=new Paint();
paint.setColor(Color.WHITE);
x=100;
y=100;
w=this.getWidth();//当前视区的宽
// h=this.getHeight();//当前视区的高
}
public void gameLogic(){
canvas.drawText("hello",x,y,paint);
sfh.unlockCanvasAndPost(canvas);
}
}
清屏操作即在原来的图形上覆盖一层
public void gameLogic(){
canvas.drawColor(Color.BLACK);//清屏操作
canvas.drawText("hello",x,y,paint);
sfh.unlockCanvasAndPost(canvas);
}
控制每次刷新的时间:在线程中记录开始时间和结束时间,判断差值与定义的时间比较
获取当前系统时间:System.currentTimeMillis();
@Override
public void run() {
while (runFlag){
x++;
long begin=System.currentTimeMillis();
gameLogic();
long end=System.currentTimeMillis();
try {
if(end-begin<50){
Thread.sleep(50-(end-begin));
}
}catch (Exception e){
e.printStackTrace();
}
}
}