在那本书用的是GameCanvas,我就用surfaceView实现了和实例2相同的效果
效果图:
下面给出MainView 的代码
Java代码
package com.wjh.demon_3;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class MainView extends SurfaceView implements Callback,Runnable{
int keyCode = 0;
String keyAction = "";
Thread gameThread = null;
boolean isGame = true;
SurfaceHolder holder = null;
public MainView(Context context) {
super(context);
// TODO Auto-generated constructor stub
setFocusable(true);
getHolder().addCallback(this);
holder = this.getHolder();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(isGame)
{
input();
logic();
doDraw();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//开始游戏主线程
public void start()
{
if(gameThread == null)
{
gameThread = new Thread(this);
gameThread.start();
}
}
//停止游戏主线程
public void stop()
{
isGame = false;
if(gameThread != null)
{
try {
gameThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//输入判断
public void input()
{
}
//逻辑判断
public void logic()
{
}
public void doDraw()
{
Canvas c = null;
try
{
c = holder.lockCanvas();
synchronized (holder) {
paint(c);
}
}finally{
if(c != null)
{
holder.unlockCanvasAndPost(c);
}
}
}
//画图
public void paint(Canvas canvas)
{
Paint backGround = new Paint();
backGround.setColor(Color.BLACK);
//清屏
canvas.drawRect(0, 0, getWidth(), getHeight(), backGround);
//设置画笔颜色
Paint cPaint = new Paint();
cPaint.setColor(Color.BLUE);
cPaint.setTextSize(20);
//输出按键的设备码
canvas.drawText("KeyCode:", 10, 20,cPaint);
canvas.drawText(""+keyCode,120,20,cPaint);
//输出按键的设备名
canvas.drawText("KeyAction:", 10, 80, cPaint);
canvas.drawText(keyAction, 120, 80, cPaint);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
stop();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
this.keyCode = keyCode;
switch(keyCode)
{
case KeyEvent.KEYCODE_DPAD_UP:
this.keyAction = "UP";
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
this.keyAction = "DOWN";
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
this.keyAction = "LEFT";
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
this.keyAction = "RIGHT";
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
this.keyAction = "CENTER";
break;
default:
this.keyAction="NONE";
break;
}
return super.onKeyDown(keyCode, event);
}
}