Android 游戏开发 SurfaceView框架


SurfaceView和View的明显不同在于Surface不需要通过线程来更新视图,但在绘制之前必须使用lockCanvas方法锁定画布,并得 到画布,然后绘制,完成后用unlockCanvasAndPost方法解锁画布。SurfaceView类的事件处理和View一样。
绘制界面的类:

1. package com.yarin.android.Examples_05_02; 2. 3. import android.content.Context; 4. import android.graphics.Canvas; 5. import android.graphics.Color; 6. import android.graphics.Paint; 7. import android.view.SurfaceHolder; 8. import android.view.SurfaceView; 9. 10. public class GameSurfaceView extends SurfaceView 11. 12. implements SurfaceHolder.Callback,Runnable 13. { 14. //控制循环 15. boolean mbLoop = false; 16. 17. //定义SurfaceHolder对象 18. SurfaceHolder mSurfaceHolder = null; 19. int miCount = 0; 20. int y = 50; 21. 22. 23. public GameSurfaceView(Context context) 24. { 25. super(context); 26. 27. // 实例化SurfaceHolder 28. mSurfaceHolder = this.getHolder(); 29. 30. // 添加回调 31. mSurfaceHolder.addCallback(this); 32. this.setFocusable(true); 33. 34. mbLoop = true; 35. } 36. 37. 38. // 在surface的大小发生改变时激发 39. public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) 40. { 41. 42. } 43. 44. // 在surface创建时激发 45. public void surfaceCreated(SurfaceHolder holder) 46. { 47. //开启绘图线程 48. new Thread(this).start(); 49. } 50. 51. // 在surface销毁时激发 52. public void surfaceDestroyed(SurfaceHolder holder) 53. { 54. // 停止循环 55. mbLoop = false; 56. } 57. 58. // 绘图循环 59. public void run() 60. { 61. while (mbLoop) 62. { 63. try 64. { 65. Thread.sleep(200); 66. } 67. catch (Exception e) 68. { 69. 70. } 71. synchronized( mSurfaceHolder ) 72. { 73. Draw(); 74. } 75. 76. } 77. } 78. 79. // 绘图方法 80. public void Draw() 81. { 82. //锁定画布,得到canvas 83. Canvas canvas= mSurfaceHolder.lockCanvas(); 84. 85. if (mSurfaceHolder==null || canvas == null ) 86. { 87. return; 88. } 89. 90. if (miCount < 100) 91. { 92. miCount++; 93. } 94. else 95. { 96. miCount = 0; 97. } 98. // 绘图 99. Paint mPaint = new Paint(); 100. mPaint.setAntiAlias(true); 101. mPaint.setColor(Color.BLACK); 102. //绘制矩形--清屏作用 103. canvas.drawRect(0, 0, 320, 480, mPaint); 104. switch (miCount % 4) 105. { 106. case 0: 107. mPaint.setColor(Color.BLUE); 108. break; 109. case 1: 110. mPaint.setColor(Color.GREEN); 111. break; 112. case 2: 113. mPaint.setColor(Color.RED); 114. break; 115. case 3: 116. mPaint.setColor(Color.YELLOW); 117. break; 118. default: 119. mPaint.setColor(Color.WHITE); 120. break; 121. } 122. 123. canvas.drawCircle((320 - 25) / 2, y, 50, mPaint); 124. // 绘制后解锁,绘制后必须解锁才能显示 125. mSurfaceHolder.unlockCanvasAndPost(canvas); 126. } 127. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值