android游戏开发学习笔记五(学习书籍 Android游戏编程之从零开始)
/**
*剪切动画+移动位图
*
*@author岳振华
*
*/
publicclassClipSurfaceViewextendsSurfaceViewimplementsCallback,Runnable{
privateSurfaceHoldersfh;
privateintscreenX,screenY;//屏幕大小
privateThreadthread;
privatebooleanflag;
privatePaintpaint,paint2;
privateCanvascanvas;
privateBitmapfish,water;
privateintcurrentFream=0;
privatefloatbmpX,bmpY;
publicClipSurfaceView(Contextcontext){
super(context);
sfh=this.getHolder();
sfh.addCallback(this);
paint=newPaint();
paint2=newPaint();
paint.setColor(Color.RED);
paint2.setColor(Color.WHITE);
paint.setAntiAlias(true);
this.setFocusable(true);
fish=BitmapFactory.decodeResource(this.getResources(),R.drawable.fish);
water=BitmapFactory.decodeResource(this.getResources(),R.drawable.water);
}
@Override
publicvoidsurfaceCreated(SurfaceHolderholder){
screenX=getWidth();
screenY=getHeight();
//宽度刚好填满屏幕
bmpX=-water.getWidth()+screenX;
//高度是屏幕高度-图片高度
bmpY=screenY-water.getHeight();
flag=true;
thread=newThread(this);
thread.start();
}
@Override
publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,intheight){
}
@Override
publicvoidsurfaceDestroyed(SurfaceHolderholder){
flag=false;
}
@SuppressWarnings("static-access")
@Override
publicvoidrun(){
while(flag){
try{
//begin
longbegin=System.currentTimeMillis();
draw();
logic();
//end
longend=System.currentTimeMillis();
if(end-begin<50){
thread.sleep(50-(end-begin));
}
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
/**
*绘图
*/
privatevoiddraw(){
try{
canvas=sfh.lockCanvas();
if(null!=canvas){
canvas.drawColor(Color.WHITE);
//设置可见区域的大小
canvas.save();
canvas.clipRect(0,0,fish.getWidth()/10,fish.getHeight());
//绘制鱼
canvas.drawBitmap(fish,-currentFream*fish.getWidth()/10,0,paint);
canvas.restore();
//绘制水
canvas.drawBitmap(water,bmpX,bmpY,paint2);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
if(null!=canvas){
sfh.unlockCanvasAndPost(canvas);
}
}
}
/**
*游戏逻辑
*/
privatevoidlogic(){
currentFream++;
if(currentFream>=10){
currentFream=0;
}
if(bmpX<0){
bmpX+=5;
}else{
bmpX=-water.getWidth()+screenX;
}
}
}