首页 > 系统 > Android > 正文

android双缓冲技术实例详解

2019-10-24 20:36:15
字体:
来源:转载
供稿:网友

这篇文章主要介绍了android双缓冲技术实例详解,需要的朋友可以参考下

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

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

先贴出View类代码:

 

 
  1. package com.lbz.pack.test; 
  2.  
  3. import android.content.Context; 
  4. import android.graphics.Bitmap; 
  5. import android.graphics.Canvas; 
  6. import android.graphics.Paint; 
  7. import android.graphics.Bitmap.Config; 
  8. import android.graphics.drawable.BitmapDrawable; 
  9. import android.view.KeyEvent; 
  10. import android.view.MotionEvent; 
  11. import android.view.View; 
  12. public class GameView extends View implements Runnable 
  13. /* 声明Bitmap对象 */ 
  14. Bitmap mBitQQ = null
  15. Paint mPaint = null
  16. /* 创建一个缓冲区 */ 
  17. Bitmap mSCBitmap = null
  18. /* 创建Canvas对象 */ 
  19. Canvas mCanvas = null;  
  20. public GameView(Context context) 
  21. super(context); 
  22. /* 装载资源 */ 
  23. mBitQQ = ((BitmapDrawable) getResources().getDrawable(R.drawable.qq)).getBitmap(); 
  24. /* 创建屏幕大小的缓冲区 */ 
  25. mSCBitmap=Bitmap.createBitmap(320, 480, Config.ARGB_8888);  
  26. /* 创建Canvas */ 
  27. mCanvas = new Canvas();  
  28. /* 设置将内容绘制在mSCBitmap上 */ 
  29. mCanvas.setBitmap(mSCBitmap);  
  30. mPaint = new Paint(); 
  31. /* 将mBitQQ绘制到mSCBitmap上 */ 
  32. mCanvas.drawBitmap(mBitQQ, 0, 0, mPaint); 
  33. /* 开启线程 */ 
  34. new Thread(this).start(); 
  35. public void onDraw(Canvas canvas) 
  36. super.onDraw(canvas); 
  37. /* 将mSCBitmap显示到屏幕上 */ 
  38. canvas.drawBitmap(mSCBitmap, 0, 0, mPaint); 
  39. // 触笔事件 
  40. public boolean onTouchEvent(MotionEvent event) 
  41. return true
  42. // 按键按下事件 
  43. public boolean onKeyDown(int keyCode, KeyEvent event) 
  44. return true
  45. // 按键弹起事件 
  46. public boolean onKeyUp(int keyCode, KeyEvent event) 
  47. return false
  48. public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) 
  49. return true
  50. /** 
  51. * 线程处理 
  52. */ 
  53. public void run() 
  54. while (!Thread.currentThread().isInterrupted()) 
  55. try 
  56. Thread.sleep(100); 
  57. catch (InterruptedException e) 
  58. Thread.currentThread().interrupt(); 
  59. //使用postInvalidate可以直接在线程中更新界面 
  60. postInvalidate(); 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表