android游戏开发学习笔记三(学习书籍 Android游戏编程之从零开始)

/**

*画笔

*

*@author岳振华

*

*/

@SuppressWarnings("unused")

publicclassPaintSrufaceViewextendsSurfaceViewimplementsCallback,Runnable{

privateSurfaceHoldersfh;

privateThreadthread;

privateintsurfaceW,surfaceH;

privateCanvascanvas;

privatebooleanflag;//surfaceView是否销毁的标志位

publicPaintSrufaceView(Contextcontext){

super(context);

/**********画图所必需*********************/

sfh=this.getHolder();//获得surfaceHolder对象

sfh.addCallback(this);

thread=newThread(this);

this.setKeepScreenOn(true);//保持屏幕常亮

this.setFocusable(true);

/********************************************/

}

/**

*开始动画

*/

@Override

publicvoidstartAnimation(Animationanimation){

super.startAnimation(animation);

}

/****************************callback的几个方法********************/

/**

*当Surface第一次创建后会立即调用该函数一般情况下都是在另外的线程来绘制界面,所以不要在这个函数中绘制Surface

*/

@Override

publicvoidsurfaceCreated(SurfaceHolderholder){

surfaceW=this.getWidth();

surfaceH=this.getHeight();

thread=newThread(this);

flag=true;

thread.start();//开启线程

}

/**

*当Surface的状态(大小和格式)发生变化的时候会调用该函数在surfaceCreated调用后该函数至少会被调用一次

*/

@Override

publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,intheight){

}

@Override

publicvoidsurfaceDestroyed(SurfaceHolderholder){

flag=false;

}

/****************************callback的几个方法********************/

/**

*绘图方法

*/

privatevoiddraw(){

try{

//获得canvas实例

canvas=sfh.lockCanvas();

if(canvas!=null){

//利用填充画布,刷屏

canvas.drawColor(Color.BLACK);

/****************画圆*****************/

//消除锯齿前

Paintpaint1=newPaint();

paint1.setColor(Color.YELLOW);

canvas.drawCircle(50,50,20,paint1);

//消除锯齿后

paint1.setAntiAlias(true);

canvas.drawCircle(100,50,20,paint1);

/***************************************/

/************写文本********************/

Paintpaint3=newPaint();

paint3.setColor(Color.RED);

canvas.drawText("无透明",100,200,paint3);

//半透明

Paintpaint2=newPaint();

paint2.setColor(Color.RED);

paint2.setAlpha(0x77);

canvas.drawText("半透明",100,220,paint2);

/**************************************/

/*************锚点**********************/

//-----设置绘制文本的锚点

canvas.drawText("锚点",20,90,newPaint());

Paintpaint4=newPaint();

paint4.setColor(Color.GREEN);

//设置以文本的中心点绘制

paint4.setTextAlign(Paint.Align.CENTER);

canvas.drawText("锚点",20,105,paint4);

}

}catch(Exceptione){

e.printStackTrace();

}finally{

if(null!=canvas){

sfh.unlockCanvasAndPost(canvas);//提交画布

}

}

}

@SuppressWarnings("static-access")

@Override

publicvoidrun(){

while(flag)

{

//绘图

draw();

try{

thread.sleep(100);

}catch(InterruptedExceptione){

e.printStackTrace();

}

}

}

}

相关推荐