Android SurfaceView使用例子


Android SurfaceView使用例子:

做游戏一般用SurfaceView

  1. package com.himi;   
  2. import android.content.Context;   
  3. import android.graphics.Canvas;   
  4. import android.graphics.Color;   
  5. import android.graphics.Paint;   
  6. import android.view.SurfaceHolder;   
  7. import android.view.SurfaceView;   
  8. import android.view.SurfaceHolder.Callback;   
  9. import android.view.animation.Animation;   
  10. /**  
  11. * @author Himi  
  12. */   
  13. public class MySurfaceView extends SurfaceView implements Callback, Runnable {// 备注1    
  14. private SurfaceHolder sfh;   
  15. private Thread th;   
  16. private Canvas canvas;   
  17. private Paint paint;   
  18. private int ScreenW, ScreenH;   
  19. public MySurfaceView(Context context) {   
  20. super(context);   
  21. th = new Thread(this);   
  22. sfh = this.getHolder();   
  23. sfh.addCallback(this); // 备注1    
  24. paint = new Paint();   
  25. paint.setAntiAlias(true);   
  26. paint.setColor(Color.RED);   
  27. this.setKeepScreenOn(true);// 保持屏幕常亮    
  28. }   
  29. @Override   
  30. public void startAnimation(Animation animation) {   
  31. super.startAnimation(animation);   
  32. }   
  33. public void surfaceCreated(SurfaceHolder holder) {   
  34. ScreenW = this.getWidth();// 备注2    
  35. ScreenH = this.getHeight();   
  36. th.start();   
  37. }   
  38. private void draw() {   
  39. try {   
  40. canvas = sfh.lockCanvas(); // 得到一个canvas实例    
  41. canvas.drawColor(Color.WHITE);// 刷屏    
  42. canvas.drawText("Himi"100100, paint);// 画文字文本    
  43. canvas.drawText("这就是简单的一个游戏框架"100130, paint);   
  44. sfh.unlockCanvasAndPost(canvas); // 将画好的画布提交    
  45. catch (Exception ex) {   
  46. finally { // 备注3    
  47. if (canvas != null)   
  48. sfh.unlockCanvasAndPost(canvas);   
  49. }   
  50. }   
  51. public void run() {   
  52. while (true) {   
  53. draw();   
  54. try {   
  55. Thread.sleep(100);   
  56. catch (InterruptedException e) {   
  57. // TODO Auto-generated catch block    
  58. e.printStackTrace();   
  59. }   
  60. }   
  61. }   
  62. public void surfaceChanged(SurfaceHolder holder, int format, int width,   
  63. int height) {   
  64. }   
  65. public void surfaceDestroyed(SurfaceHolder holder) {   
  66. // TODO Auto-generated method stub    
  67. }   
  68. }   

相关内容