View的绘图机制存在如下缺陷:
由于上述的几个缺陷,通过自定义的View来绘图性能底下,Android提供了一个SurfaceView来替代View,在游戏绘图方面表现的更加出色。
SurfaceView的绘图机制
SurfaceView一般会与SurfaceHolder结合使用,SurfaceHolder用于向与之关联的SurfaceView上绘图,调用getHolder()方法获取SurfaceView上关联的SurfaceHolder。
SurfaceHolder提供了如下的方法来获取Canvas对象:
如果将上面两种方法用于同一个SurfaceView时,返回的是同一个canvas对象,但是当程序调用第二个方法取指定区域的canvas时,SurfaceView将只对Rect规定的区域进行重新绘制,这样就能提高View的重绘效率。
获得了相应的canvas对象之后,接下来就进行绘图工作,绘图完成了再调用unlockCanvasAndPost(canvas)方法。需要注意的是当调用unlockCanvasAndPost后,之前绘制的图像还处于缓冲之中,再次调用lockCanvas()方法锁定的区域可能会“遮挡”它。导致刷新失败。
下面用一个实例来演示
public class MainActivity extends Activity {
//用于向SurfaceView上绘制图像,组件等
private SurfaceHolder holder;
//画笔工具,用于绘制
private Paint paint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paint = new Paint();
SurfaceView surface = (SurfaceView) findViewById(R.id.show);
//SurfaceHolder对象
holder = surface.getHolder();
/**
* 给SurfaceHolder添加一个CallBack实例
* 重写了surfaceCreated(SurfaceHolder holder)方法
*/
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
//将整个SurfaceView上的canvas获取到,在canvas上绘图
Canvas canvas = holder.lockCanvas();
//将背景加载为Bitmap
Bitmap bg = BitmapFactory.decodeResource(
MainActivity.this.getResources()
,R.mipmap.ic_launcher);
//开始绘制
canvas.drawBitmap(bg, 0, 0, null);
//unlock画布
holder.unlockCanvasAndPost(canvas);
// 再次锁定,防止被覆盖
canvas = holder.lockCanvas(new Rect(0, 0, 0, 0));
holder.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
surface.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int cx = (int) event.getX();
int cy = (int) event.getY();
//局部锁定SurfaceView,只更新一部分图像
Canvas canvas = holder.lockCanvas(new Rect(cx - 50,
cy - 50, cx + 50, cy + 50));
//保存当前canvas状态
canvas.save();
//旋转画布,设置画笔的颜色
canvas.rotate(30,cx,cy);
paint.setColor(Color.RED);
//绘制一个长方形
canvas.drawRect(cx - 40, cy - 40, cx, cy, paint);
//恢复canvas之前保存的状态
canvas.restore();
paint.setColor(Color.GREEN);
canvas.drawRect(cx, cy, cx + 40, cy + 40, paint);
holder.unlockCanvasAndPost(canvas);
}
return false;
}
});
}
}
原文地址:http://blog.csdn.net/jing_unique_da/article/details/44034429