surfaceView开发游戏初涉一

在使用surfaceView开发一个小游戏的过程当中,遇到的一些问题记录:java

1、使用android

    类A继承自surfaceView,在构造函数中使用getHolder()获得SurfaceHolder对象,SurfaceHolder能够获得Canvas对象,有了Canvas对象就能够作画图相关的操做了。
git

   

SurfaceHolder holder = getHolder();
Canvas canvas = holder.lock();
if(canvas == null){
    return;
}
canvas.save();
    //画图相关操做
canvas.restore();
holder.unlockCanvasAndPost(canvas);

    以上就是surfaceView的通用使用方式了,能够在线程中使用(这是与View的最大区别)。github

    以上代码有几个注意点json

        一、必须判断canvas为空,若是使用线程循环操做时,在应用切换到后台,或退出应用时,canvas获得的对象是为空的。canvas

        二、必须为canvas绘制背景图,若是没有背景图,绘制的图像在执行几回循环后,就会出现重影(在这个地方被坑了半天j_0008.gif)。
微信

2、开发游戏的时候参考了http://tanqisen.github.io/blog/2013/09/13/develop-android-wechat-flight-game-step-by-step-1/   这篇文章,博主写的游戏是一个小的框架,很到的体现了面向对象的思想。在这篇文章中博主的资源文件(.plist)是从微信上扣出来的。也没有对旋转的图片进行处理。这里补上个人一些处理经验。框架

        一、plist图像文件的生成和json字符串的生成。
ide

                生成以上文件使用了一个破解版的工具TexturePacker。在处理这个问题时一个有游戏开发经验的同事给了我很大的帮助。很是感谢他。函数

        二、对于在plist中被旋转图片的处理。

                前提是使用TexturePacker生成的json格式的文件。将http://tanqisen.github.io/blog/2013/09/13/develop-android-wechat-flight-game-step-by-step-1/的代码下载下来后,找到GameContext中的displayArt()方法。

                

canvas.save();
		Sprite s = spriteManager.getSprite(a.sprite);
		Rect spriteFrame = a.spriteFrame();
		Rect colorRect = s.spriteColorRect;
		int left = 0,top = 0,right = 0,bottom = 0;
		if(s.isRotated()){
			int height = bmp.getWidth();
			Frame frame = s.getFrame();
			left = frame.getY()+spriteFrame.left;
			top = height-(frame.getX()+frame.getH())+spriteFrame.top;
			right = left + frame.getW();
			bottom = top + frame.getH();
			
			Matrix matrix = new Matrix();
			int px = 0,py = 0;
			px = spriteFrame.left;
			py = spriteFrame.top+height;
			matrix.setTranslate(px, py);
			matrix.postRotate(-90,px, py);
			canvas.clipRect(left, top, right, bottom);
			canvas.drawBitmap(bmp,matrix,paint);
		}else{
			left   = spriteFrame.left;
			top    = spriteFrame.top;
			right  = left + colorRect.width();
			bottom = top + colorRect.height();
			canvas.clipRect(left<viewRect.left?viewRect.left:left, top<viewRect.top?viewRect.top:top, 
					right>viewRect.right?viewRect.right:right, bottom>viewRect.bottom?viewRect.bottom:bottom);
			canvas.drawBitmap(bmp, left - colorRect.left, top - colorRect.top, paint);
		}
		canvas.restore();

这是对被旋转顺时针旋转90度的处理方法。

        结语:

                感谢Cooper的文章分享,在进入陌生的开发领域时有一位有经验的朋友帮助是很重要的。