SurfaceView在游戏开发中有着举足轻重的地位,它对于画面的控制有着更大的自由度(不像View要用handler来更新)
package com.Aina.Android;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* com.Aina.Android Pro_SurfaceView
*
* @author Aina.huang E-mail: 674023920@qq.com
* @version 创建时间:2010 Jun 9, 2010 11:22:35 AM 类说明
*/
public class MyView extends SurfaceView implements SurfaceHolder.Callback,
Runnable {
private SurfaceHolder holder;
public static int x = 100, y = 100;
public MyView(Context context) {
super(context);
Log.i("TAG", "MyView()");
holder = this.getHolder();
holder.addCallback(this);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.i("TAG", "surfaceChanged()");
}
public void surfaceCreated(SurfaceHolder holder) {
new Thread(this).start();
Log.i("TAG", "surfaceCreated()");
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("TAG", "surfaceDestroyed()");
}
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
synchronized (holder) {
this.onDraw();
}
Thread.sleep(100);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void onDraw() {
Canvas canvas = holder.lockCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLACK);
Log.i("TAG", canvas.getWidth() + "|" + canvas.getHeight());
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
canvas.drawCircle(x, y, 30, paint);
// canvas.drawRect(x, y, a, b, paint);
holder.unlockCanvasAndPost(canvas);
}
}
package com.Aina.Android;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
public class Test_SurfaceView extends Activity {
/** Called when the activity is first created. */
private MyView mv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mv = new MyView(this);
setContentView(mv);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:// 向下
MyView.y += 5;
break;
case KeyEvent.KEYCODE_DPAD_UP:// 向上
MyView.y -= 5;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:// 向左
MyView.x -= 5;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:// 向右
MyView.x += 5;
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
MyView.x = x;
MyView.y = y;
return super.onTouchEvent(event);
}
}