android double buffering technology example details

  • 2020-06-01 10:58:50
  • OfStack

The SurfaceView class in Android is the double-buffering mechanism. Therefore, SurfaceView should be used instead of View when developing Android games, which is more efficient and has better functions. To make it easier to understand the double-buffering technique, here's how to implement it with View.

In the context of note 1, the core technique of double buffering is to first draw all the graphs to be drawn by setBitmap method to one Bitmap, and then call drawBitmap method to draw the Bitmap and display it on the screen. The specific implementation code is as follows:

First post the View class code:


package com.lbz.pack.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
public class GameView extends View implements Runnable
{
 /*  The statement Bitmap object  */
 Bitmap mBitQQ = null;
 Paint  mPaint = null;
 /*  create 1 A buffer  */
 Bitmap mSCBitmap = null;
 /*  create Canvas object  */
 Canvas mCanvas = null;  
 public GameView(Context context)
 {
 super(context);
 /*  Load resources  */
 mBitQQ = ((BitmapDrawable) getResources().getDrawable(R.drawable.qq)).getBitmap();
 /*  Create a buffer the size of the screen  */
 mSCBitmap=Bitmap.createBitmap(320, 480, Config.ARGB_8888); 
 /*  create Canvas */
 mCanvas = new Canvas(); 
 /*  Set to draw the content in mSCBitmap on  */
 mCanvas.setBitmap(mSCBitmap); 
 mPaint = new Paint();
 /*  will mBitQQ Drawn to the mSCBitmap on  */
 mCanvas.drawBitmap(mBitQQ, 0, 0, mPaint);
 /*  Open the thread  */
 new Thread(this).start();
 }
 public void onDraw(Canvas canvas)
 {
 super.onDraw(canvas);
 /*  will mSCBitmap Put it on the screen  */
 canvas.drawBitmap(mSCBitmap, 0, 0, mPaint);
 }
 //  Stylus events 
 public boolean onTouchEvent(MotionEvent event)
 {
 return true;
 }
 //  Key down event 
 public boolean onKeyDown(int keyCode, KeyEvent event)
 {
 return true;
 }
 //  Button bounce event 
 public boolean onKeyUp(int keyCode, KeyEvent event)
 {
 return false;
 }
 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
 {
 return true;
 }
 /**
 *  threading 
 */
 public void run()
 {
 while (!Thread.currentThread().isInterrupted())
 {
  try
  {
  Thread.sleep(100);
  }
  catch (InterruptedException e)
  {
  Thread.currentThread().interrupt();
  }
  // use postInvalidate You can update the interface directly in a thread 
  postInvalidate();
 }
 }
}

Related articles: