android游戏开发学习笔记二(学习书籍 Android游戏编程之从零开始)
/**
*画布
*
*@author岳振华
*
*/
@SuppressWarnings("unused")
publicclassCanvasSrufaceViewextendsSurfaceViewimplementsCallback,Runnable{
privateSurfaceHoldersfh;
privateThreadthread;
privateintsurfaceW,surfaceH;
privatePaintpaint;
privateCanvascanvas;
privatePaintFlagsDrawFilterdrawFilter=newPaintFlagsDrawFilter(0,Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
publicCanvasSrufaceView(Contextcontext){
super(context);
/**********画图所必需*********************/
sfh=this.getHolder();//获得surfaceHolder对象
sfh.addCallback(this);
thread=newThread(this);
paint=newPaint();//新建画笔
paint.setColor(Color.RED);//设置画笔颜色
paint.setAntiAlias(true);//消除锯齿
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);
thread.start();//开启线程
}
/**
*当Surface的状态(大小和格式)发生变化的时候会调用该函数在surfaceCreated调用后该函数至少会被调用一次
*/
@Override
publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,intheight){
}
@Override
publicvoidsurfaceDestroyed(SurfaceHolderholder){
}
/****************************callback的几个方法********************/
/**
*绘图方法
*/
privatevoiddraw(){
try{
//获得canvas实例
canvas=sfh.lockCanvas();
if(canvas!=null){
//paint=newPaint();
//paint.setAntiAlias(true);
//消除锯齿
canvas.setDrawFilter(drawFilter);
//利用填充画布,刷屏
canvas.drawColor(Color.BLACK);
//绘制文本
canvas.drawText("岳振华",50,50,paint);
//绘制象素点
canvas.drawPoint(10,20,paint);
//绘制多个象素点(同一直线上的)
canvas.drawPoints(newfloat[]{10,30,30,30},paint);
//绘制直线
canvas.drawLine(20,40,40,40,paint);
//绘制多条直线
canvas.drawLines(newfloat[]{20,50,40,50,20,60,40,60},paint);
//方法一:绘制矩形
canvas.drawRect(30,60,60,90,paint);
//方法二:绘制矩开
Rectrect=newRect(70,60,100,100);
canvas.drawRect(rect,paint);
//绘制圆角矩形
RectFrectF=newRectF(30,100,60,150);
canvas.drawRoundRect(rectF,2,2,paint);
//绘制圆形
canvas.drawCircle(100,200,10,paint);
//绘制弧形
canvas.drawArc(newRectF(150,//第一个和第三个参数表半径
20,//
160,//第二个参数表弧度
70),//
0,180,true,paint);
//绘制椭圆
canvas.drawOval(newRectF(200,50,260,70),paint);
//绘制指定路径的图形(多边形)
Pathpath=newPath();
//设置路径起点
path.moveTo(160,150);
//路线1
path.lineTo(200,150);
//路线2
path.lineTo(180,200);
//路线3
path.lineTo(160,180);
//路径结束
path.close();
canvas.drawPath(path,paint);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
if(null!=canvas){
sfh.unlockCanvasAndPost(canvas);//提交画布
}
}
}
@SuppressWarnings("static-access")
@Override
publicvoidrun(){
//绘图
draw();
try{
thread.sleep(100);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}