SurfaceView在游戏开发中有着举足轻重的地位,它对于画面的控制有着更大的自由度(不像View要用handler来更新,关于View的),但这方面的参考资料并不是太多,能找到的例子都有点喧宾夺主的感觉,不能把使用的流程清晰展示出来,下面是个简单的示例,力求把流程清楚展示,其他的可简则简。
程序效果——1:用线程画一个蓝色的长方形。
JAVA代码
package com.hyzhou.surfaceviewdemo; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new MyView(this)); } private class MyView extends SurfaceView implements SurfaceHolder.Callback { /** * @param context */ SurfaceHolder holder; public MyView(Context context) { super(context); // TODO Auto-generated constructor stub holder=this.getHolder(); holder.addCallback(this); } @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 new Thread(new MyThread()).start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } class MyThread implements Runnable { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { // TODO Auto-generated method stub Canvas canvas = holder.lockCanvas(null);//获取画布 Paint mPaint = new Paint(); mPaint.setColor(Color.BLUE); canvas.drawRect(new RectF(40,60,80,80), mPaint); //前2个参数代表右上角坐标,后2个参数代表右下角坐标 holder.unlockCanvasAndPost(canvas);//解锁画布,提交画好的图像 } } } }