SurfaceView double buffer test

This is a small test before the dirty rectangle drawing research of SurfaceView.

Android SurfaceView mainly updates the view in the worker thread, using a double buffering mechanism.

Because the time to draw to the device is much shorter than the time to save to the memory, drawing all the primitives to the memory and then drawing to the device can optimize the display speed.

Find some SurfaceView information, the meaning is probably as follows:

Draw the first frame using buffer1, when unlocked, draw buffer1 to the device ,

Draw the second frame using buffer2, after unlocking, draw buffer2 to the device,

Draw the third frame using buffer1,

And so on. . .

Write the test code:

public class DirtyRectActivity extends BaseActivity implements SurfaceHolder.Callback{ private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private WorkThread mThread = new WorkThread(); @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_dirty_dirty_dirty ); mSurfaceView = (SurfaceView)findViewById(R.id.surface); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mSurface classHolder. = false; private int mFrame = 0; public void run() {while (!interrupted() && !mStop) {try {sleep(1000);} catch (InterruptedException e) {} draw(mFrame++);} }; public void stopThread(){ mStop = true; try {join();} catch (InterruptedException e) {}}} private void draw(int frame){ Paint paint = new Paint(); paint.setColor(Color.parseColor("red")); paint.setTextSize( 16f); Canvas canvas = null; try {canvas = mSurfaceHolder.lockCanvas(); String text = ""+frame; canvas.drawText(text, 20*frame, 111, paint);} catch (Exception e) {} finally {if (canvas != null){ try {mSurfaceHolder.unlockCanvasAndPost(canvas);} catch (Exception e2) {}}}} @Override public void surfaceCreated(SurfaceHolder holder) {mThread.start();} @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} @Override public void surfaceDestroyed(SurfaceHolder holder) {mThread.stopThread(); }}

Execution effect:

This is one of the effects.

Tested on my mobile phone, the effect is that 2 frames are used alternately. It seems that the number of buffers used by SurfaceView is not uniform on different devices.

Leave a Comment

Your email address will not be published.