首页 > 系统 > Android > 正文

android双缓冲技术实例详解

2020-04-11 11:48:35
字体:
来源:转载
供稿:网友

Android中的SurfaceView类就是双缓冲机制。因此,在进行Android游戏开发时应尽量使用SurfaceView而不要使用View,这样的话效率较高,并且SurfaceView的功能也更加完善。为了更容易的了解双缓冲技术,下面介绍用View实现双缓冲的方法。

在此需要说明一下,双缓冲的核心技术就是先通过setBitmap方法将要绘制的所有的图形绘制到一个Bitmap上,然后再来调用drawBitmap方法绘制出这个Bitmap,显示在屏幕上。其具体的实现代码如下:

先贴出View类代码:

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{ /* 声明Bitmap对象 */ Bitmap mBitQQ = null; Paint  mPaint = null; /* 创建一个缓冲区 */ Bitmap mSCBitmap = null; /* 创建Canvas对象 */ Canvas mCanvas = null;   public GameView(Context context) { super(context); /* 装载资源 */ mBitQQ = ((BitmapDrawable) getResources().getDrawable(R.drawable.qq)).getBitmap(); /* 创建屏幕大小的缓冲区 */ mSCBitmap=Bitmap.createBitmap(320, 480, Config.ARGB_8888);  /* 创建Canvas */ mCanvas = new Canvas();  /* 设置将内容绘制在mSCBitmap上 */ mCanvas.setBitmap(mSCBitmap);  mPaint = new Paint(); /* 将mBitQQ绘制到mSCBitmap上 */ mCanvas.drawBitmap(mBitQQ, 0, 0, mPaint); /* 开启线程 */ new Thread(this).start(); } public void onDraw(Canvas canvas) { super.onDraw(canvas); /* 将mSCBitmap显示到屏幕上 */ canvas.drawBitmap(mSCBitmap, 0, 0, mPaint); } // 触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } // 按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { return true; } // 按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return false; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } /** * 线程处理 */ public void run() { while (!Thread.currentThread().isInterrupted()) {  try  {  Thread.sleep(100);  }  catch (InterruptedException e)  {  Thread.currentThread().interrupt();  }  //使用postInvalidate可以直接在线程中更新界面  postInvalidate(); } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表