1.概念
SurfaceView是View类的子类,可以直接从内存或者DMA等硬件接口取得图像数据,是个非常重要的绘图视图。它的特性是:可以在主线程之外的 线程中向屏幕绘图上。这样可以避免画图任务繁重的时候造成主线程阻塞,从而提高了程序的反应速度。在游戏开发中多用到SurfaceView,游戏中的背 景、人物、动画等等尽量在画布canvas中画出。
2.实现方法
1)实现步骤
a.继承SurfaceView
b.实现SurfaceHolder.Callback接口
2)需要重写的方法
(1) surfaceChanged(SurfaceHolder holder, format, width, height){}
(2) surfaceCreated(SurfaceHolder holder){}
(3) surfaceDestroyed(SurfaceHolder holder) {}
3)SurfaceHolder
SurfaceHolder,surface的控制器,用来操纵surface。处理它的Canvas上画的效果和动画,控制表面,大小,像素等。
几个需要注意的方法:
(1)、 addCallback(SurfaceHolder.Callback callback);
(2)、 Canvas lockCanvas();
(3)、 Canvas lockCanvas(Rect dirty);
(4)、 unlockCanvasAndPost(Canvas canvas);
4)总结整个过程
继承SurfaceView并实现SurfaceHolder.Callback接口 ----> SurfaceView.getHolder()获得SurfaceHolder对象 ---->SurfaceHolder.addCallback(callback)添加回调函数---->SurfaceHolder.lockCanvas()获得Canvas对象并锁定画布----> Canvas绘画 ---->SurfaceHolder.unlockCanvasAndPost(Canvas canvas)结束锁定画图,并提交改变,将图形显示。
下面是一个完整的案例:
public class ViewTest extends Activity {
@Override
onCreate(Bundle savedInstanceState) {
.onCreate(savedInstanceState);
setContentView( MyView());
}
MyView SurfaceView SurfaceHolder.Callback
{
SurfaceHolder holder;
MyThread myThread;
MyView(Context context) {
(context);
holder = .getHolder();
holder.addCallback();
myThread = MyThread(holder); }
@Override
surfaceChanged(SurfaceHolder holder, format, width,
height) {
}
@Override
surfaceCreated(SurfaceHolder holder) {
myThread.isRun = ;
myThread.start();
}
@Override
surfaceDestroyed(SurfaceHolder holder) {
myThread.isRun = ;
}
}
MyThread Thread
{
SurfaceHolder holder;
isRun ;
MyThread(SurfaceHolder holder)
{
.holder =holder;
isRun = ;
}
@Override
run()
{
count = 0;
(isRun)
{
Canvas c = ;
{
(holder){
c = holder.lockCanvas(); c.drawColor(Color.BLACK); Paint p = Paint(); p.setColor(Color.WHITE);
Rect r = Rect(100, 50, 300, 250);
c.drawRect(r, p);
c.drawText("这是第"+(count++)+"秒", 100, 310, p);
Thread.sleep(1000); }
}
(Exception e) {
e.printStackTrace();
}
{
(c!= )
{
holder.unlockCanvasAndPost(c); }
}
}
}
}
}