在使用surfaceView开发一个小游戏的过程中,遇到的一些问题记录:
一、使用
,,,,类一个继承自surfaceView,在构造函数中使用getHolder()得到SurfaceHolder对象,SurfaceHolder可以得到画布对象,有了画布对象就可以做画图相关的操作了。
,,
SurfaceHolder holder =, getHolder (); Canvas Canvas =, holder.lock (); 如果(canvas ==, null) { ,,,返回; } canvas.save (); ,,,//画图相关操作 canvas.restore (); holder.unlockCanvasAndPost(画布);
,,,,以上就是surfaceView的通用使用方式了,可以在线程中使用(这是与视图的最大区别)。
,,,,以上代码有几个注意点
,,,,,,,, 1,必须判断帆布为空,如果使用线程循环操作时,在应用切换到后台,或退出应用时,帆布得到的对象是为空的。
,,,,,,,, 2,必须为画布绘制背景图,如果没有背景图,绘制的图像在执行几次循环后,就会出现重影(在这个地方被坑了半天)。
二,开发游戏的时候参考了http://tanqisen.github。io/博客/2013/09/13/develop-android-wechat-flight-game-step-by-step-1/,这篇文章,博主写的游戏是一个小的框架,很到的体现了面向对象的思想。在这篇文章中博主的资源文件(.plist)是从微信上扣出来的。也没有对旋转的图片进行处理。这里补上我的一些处理经验。
,,,,,,,, 1, plist图像文件的生成和json字符串的生成。
,,,,,,,,,,,,,,,,生成以上文件使用了一个破解版的工具TexturePacker。在处理这个问题时一个有游戏开发经验的同事给了我很大的帮助。非常感谢他。
,,,,,,,, 2,对于在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; 如果(s.isRotated ()) { int height =, bmp.getWidth (); Frame Frame =, s.getFrame (); 时间=left frame.getY () + spriteFrame.left; top =,高度(frame.getX frame.getH () + ()) + spriteFrame.top; +=right left frame.getW (); +=bottom top frame.getH (); Matrix Matrix =, new 矩阵(); int px =, 0, py =, 0; 时间=px spriteFrame.left; 时间=py spriteFrame.top +高度; matrix.setTranslate (px, py); matrix.postRotate (-90 px, py); canvas.clipRect(左,,,,对,,底部); canvas.drawBitmap (bmp、矩阵、油漆); 其他}{ left ,,=, spriteFrame.left; top ,,,=, spriteFrame.top; right ,=, left +, colorRect.width (); +=bottom top colorRect.height (); canvas.clipRect (leftviewRect.right ? viewRect.right:对,,bottom> viewRect.bottom ? viewRect.bottom:底部); canvas.drawBitmap (bmp, left 安康;colorRect.left,, top 作用;colorRect.top,,油漆); } canvas.restore ();
这是对被旋转顺时针旋转90度的处理方法。
,,,,,,,,结语:
,,,,,,,,,,,,,,,,感谢库珀的文章分享,在进入陌生的开发领域时有一位有经验的朋友帮助是很重要的。