public class SurfaceViewTest extends Activity { //SurfaceHolder负责维护SurfaceView上绘制的内容 private SurfaceHolder holder; private Paint paint; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.surface); paint=new Paint(); SurfaceView surface=(SurfaceView) findViewById(R.id.surface); //初始化SurfaceView对象 holder=surface.getHolder(); holder.addCallback(new Callback() { @Override public void surfaceDestroyed(SurfaceHolder arg0) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder arg0) { // TODO Auto-generated method stub //锁定整个SurfaceView Canvas canvas=holder.lockCanvas(); //绘制背景 Bitmap back=BitmapFactory.decodeResource(SurfaceViewTest.this.getResources(), R.drawable.ic_launcher); canvas.drawBitmap(back, 0,0, null); //绘制完成,释放画布,提交修改 holder.unlockCanvasAndPost(canvas); //重新锁一次,“持久化”上次所绘制的内容 holder.lockCanvas(new Rect(0, 0, 0, 0)); holder.unlockCanvasAndPost(canvas); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } }); //为SurfaceView绑定监听事件 surface.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { // TODO Auto-generated method stub //按下的事件 if(arg1.getAction()==MotionEvent.ACTION_DOWN){ int cx=(int) arg1.getX(); int cy=(int) arg1.getY(); //锁定SurfaceView的局部区域,只更新局部 Canvas canvas=holder.lockCanvas(new Rect(cx-50, cy-50, cx+50, cy+50)); //保存当前的状态 canvas.save(); canvas.rotate(30, cx, cy); paint.setColor(Color.GREEN); canvas.drawRect(cx-40, cy-40, cx, cy, paint); canvas.restore(); paint.setColor(Color.RED); canvas.drawRect(cx, cy, cx+40, cy+40, paint); holder.unlockCanvasAndPost(canvas); } return false; } }); } }
SurfaceView一般会与SurfaceHolder结合使用,SurfaceHolder用于向与之关联的SurfaceView上绘图,调用SurfaceView的getHolder()方法即可获取SurfaceView关联的SurfaceHolder。
SurfaceHolder提供了如下方法来获取Canvas对象。
Canvas lockCanvas():锁定SurfaceView对象,获取Surface上的Canvas。
Canvas lockCanvas(Rect dirty):锁定SurfaceView上Rect划分的区域,获取该Surface上的Canvas。
unlockCanvasAndPost(canva);
需要指出的是,当调用SurfaceHolder的 unlockCanvasAndPost方法之后,该方法之前绘制的图形还处于缓冲之中,下一次lockCanvas()方法锁定的区域可能会“遮挡”它。