用SurfaceView實現上篇View框架一樣的例子
講解寫在注釋裡
復制代碼
1 package com.example.gamesurfaceview2;
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.MotionEvent;
8 import android.view.SurfaceHolder;
9 import android.view.SurfaceHolder.Callback;
10 import android.view.SurfaceView;
11
12 //SurfaceView 還要繼承CallBack接口
13 public class MySurfaceView extends SurfaceView implements Callback,Runnable{
14
15 private SurfaceHolder sfh;
16 private Paint paint;
17 private int x,y;
18 private Thread thread;
19 private boolean flag;
20 private Canvas canvas;
21 private int w,h;
22
23 public MySurfaceView(Context context) {
24 super(context);
25 // TODO Auto-generated constructor stub
26 //通過SurfaceHolder來和Can打交道
27 sfh = this.getHolder();
28 //添加監聽
29 sfh.addCallback(this);
30 x =20;
31 y =20;
32 paint = new Paint();
33 paint.setColor(Color.WHITE);
34 setFocusable(true);
35 }
36
37 @Override
38 /**
39 * surfaceView發生改變時執行的方法
40 */
41 public void surfaceChanged(SurfaceHolder holder, int format, int width,
42 int height) {
43 // TODO Auto-generated method stub
44
45 }
46
47 @Override
48 /**
49 * surfaceView創建時執行的方法
50 */
51 public void surfaceCreated(SurfaceHolder holder) {
52 // TODO Auto-generated method stub
53 h = this.getHeight();
54 w = this.getWidth();
55 flag = true;
56 thread = new Thread(this);
57 thread.start();
58 }
59
60 /**
61 * 自己定義的繪畫調用方法
62 */
63 private void Mydraw() {
64 try {
65 // 獲取一個加鎖的畫布,防止被其他修改
66 canvas = sfh.lockCanvas();
67 if (canvas != null) {
68 //-----------利用填充矩形的方式,刷屏
69 ////繪制矩形
70 //canvas.drawRect(0,0,this.getWidth(),
71 //this.getHeight(), paint);
72 //-----------利用填充畫布,刷屏
73 // canvas.drawColor(Color.BLACK);
74 //-----------利用填充畫布指定的顏色分量,刷屏
75 // 沒重畫圖像會疊在一起
76 canvas.drawRGB(0, 0, 0);
77 canvas.drawText("Game", x, y, paint);
78 }
79 } catch (Exception e) {
80 // TODO: handle exception
81 } finally {
82 if (canvas != null)
83 // 解鎖和提交畫布
84 sfh.unlockCanvasAndPost(canvas);
85 }
86 }
87
88 @Override
89 /**
90 * surfaceView被銷毀時執行的方法
91 */
92 public void surfaceDestroyed(SurfaceHolder holder) {
93 // TODO Auto-generated method stub
94
95 }
96
97
98 @Override
99 /**
100 * 觸摸屏幕事件
101 */
102 public boolean onTouchEvent(MotionEvent event) {
103 // TODO Auto-generated method stub
104 x= (int) event.getX();
105 y= (int) event.getY();
106 return true;
107 }
108
109
110 /**
111 * 游戲邏輯
112 */
113 private void logic() {
114
115 }
116 @Override
117 public void run() {
118 while (flag) {
119 long start = System.currentTimeMillis();
120 Mydraw();
121 logic();
122 long end = System.currentTimeMillis();
123 try {
124 // 50毫秒刷新一次
125 if (end - start < 50) {
126 Thread.sleep(50 - (end - start));
127 }
128 } catch (InterruptedException e) {
129 e.printStackTrace();
130 }
131 }
132 }
133
134
135 }