Android SurfaceView Double Buffer

  • 摘要

        本文主要介绍Android SurfaceView的双缓冲机制,并给出一个测试用例来展示SurfaceView用到了两块绘图缓冲。

  • 概述

        SurfaceView的机制可以简单的用下图来表示:

Android SurfaceView Double Buffer_第1张图片

        首先,SurfaceView内部会有两块Buffer。调用lockCanvas之后,便可以在第一块Buffer上绘图了。绘完之后,调用unlockCanvasAndPost将Buffer显示再屏幕上,两个Buffer互换。

        其次,重复上面的步骤,整个过程相当于上图的右半部分。

  • 测试

        要测试它的两个Buffer很容易,下面的例子即可。

/**
 * Used to test SurfaceView double buffer mechanics.
 * @author Fred
 * 
 */
public class TestDoubleBuffer extends SurfaceView implements Callback {
	
	private boolean quit_;

	public TestDoubleBuffer(Context context) {
		super(context);
		this.getHolder().addCallback(this);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		quit_ = false;
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (!quit_) {
					// Generate coordinates for rectangle.
					int rw = 100, rh = 100;
					int sw = TestDoubleBuffer.this.getWidth();
					int sh = TestDoubleBuffer.this.getHeight();
					int left = (int) ((sw - rw) * Math.random());
					int top = (int) ((sh - rh) * Math.random());
					// Create yellow paint.
					Paint paint = new Paint();
					// Draw rectangle filled with yellow.
					SurfaceHolder holder = TestDoubleBuffer.this.getHolder();
					Canvas canvas = holder.lockCanvas();
					paint.setColor(Color.YELLOW);
					canvas.drawRect(new Rect(left, top, left + rw, top + rh),
							paint);
					holder.unlockCanvasAndPost(canvas);
					// Sleep 1 second after every draw.
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
				}
			}
		}).start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		quit_ = true;
	}

}

        该例子随机生成一个黄色的矩形,然后绘制在Buffer上,你会发现最后的结果是,在两个Buffer上生成不同的矩形,下图是其中相邻两帧的截图。

Android SurfaceView Double Buffer_第2张图片

        当不是刷屏的时候,程序中可能要做特别处理,否则会像此例一样的闪。


你可能感兴趣的:(android,android,android,double,buffer,SurfaceView,SurfaceView,SurfaceView,doublebuffer)