今天介绍一下SurfaceView的用法,SurfaceView一般与SurfaceHolder结合使用,SurfaceHolder用于向与之关联的SurfaceView上绘图,调用SurfaceView的getHolder()方法即可获取SurfaceView关联的SurfaceHolder。
SurfaceHolder提供一下几个方法来获取Canvas对象:
Canvas lockCanvas():锁定整个SurfaceView对象,获取该Surface上的Canvas。
Canvas lockCanvas(Rect dirty):锁定SurfaceView上Rect划分的区域,获取该Surface上的Canvas。
当通过lockCanvas获取指定SurfaceView上的Canvas之后,接下来程序就可以调用Canvas进行绘图,绘图完成后,调用一下方法来释放绘图、提交所绘制的图形:
unlockCanvasAndPost(canvas)。
下面直接上个实例:
1 public class SurfaceViewTest extends Activity 2 { 3 // SurfaceHolder负责维护SurfaceView上绘制的内容 4 private SurfaceHolder holder; 5 private Paint paint; 6 @Override 7 public void onCreate(Bundle savedInstanceState) 8 { 9 super.onCreate(savedInstanceState); 10 setContentView(R.layout.main); 11 paint = new Paint(); 12 SurfaceView surface = (SurfaceView) findViewById(R.id.show); 13 // 初始化SurfaceHolder对象 14 holder = surface.getHolder(); 15 holder.addCallback(new Callback() 16 { 17 @Override 18 public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, 19 int arg3) 20 { 21 } 22 23 @Override 24 public void surfaceCreated(SurfaceHolder holder) 25 { 26 // 锁定整个SurfaceView 27 Canvas canvas = holder.lockCanvas(); 28 // 绘制背景 29 Bitmap back = BitmapFactory.decodeResource( 30 SurfaceViewTest.this.getResources(), R.drawable.sun); 31 //绘制背景 32 canvas.drawBitmap(back, 0, 0, null); 33 // 绘制完成,释放画布,提交修改 34 holder.unlockCanvasAndPost(canvas); 35 //重新锁一次,"持久化"上次所绘制的内容 36 holder.lockCanvas(new Rect(0, 0, 0, 0)); 37 holder.unlockCanvasAndPost(canvas); 38 } 39 40 @Override 41 public void surfaceDestroyed(SurfaceHolder holder) 42 { 43 } 44 }); 45 //为surface的触摸事件绑定监听器 46 surface.setOnTouchListener(new OnTouchListener() 47 { 48 @Override 49 public boolean onTouch(View source, MotionEvent event) 50 { 51 // 只处理按下事件 52 if (event.getAction() == MotionEvent.ACTION_DOWN) 53 { 54 int cx = (int) event.getX(); 55 int cy = (int) event.getY(); 56 // 锁定SurfaceView的局部区域,只更新局部内容 57 Canvas canvas = holder.lockCanvas(new Rect(cx - 50, 58 cy - 50, cx + 50, cy + 50)); 59 // 保存canvas的当前状态 60 canvas.save(); 61 // 旋转画布 62 canvas.rotate(30, cx, cy); 63 paint.setColor(Color.RED); 64 // 绘制红色方块 65 canvas.drawRect(cx - 40, cy - 40, cx, cy, paint); 66 // 恢复Canvas之前的保存状态 67 canvas.restore(); 68 paint.setColor(Color.GREEN); 69 // 绘制绿色方块 70 canvas.drawRect(cx, cy, cx + 40, cy + 40, paint); 71 // 绘制完成,释放画布,提交修改 72 holder.unlockCanvasAndPost(canvas); 73 } 74 return false; 75 } 76 }); 77 } 78 }