android双缓冲技术实例详解
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(); } } }
相关文章
RecyclerView实现抖音纵向滚动ViewPager效果
这篇文章主要为大家详细介绍了RecyclerView实现抖音纵向滚动ViewPager效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2018-07-07Android编程实现的自定义弹窗(PopupWindow)功能示例
这篇文章主要介绍了Android编程实现的自定义弹窗(PopupWindow)功能,结合简单实例形式分析了Android自定义弹窗实现方法与相关注意事项,需要的朋友可以参考下2017-03-03Android自定义Spinner下拉列表(使用ArrayAdapter和自定义Adapter实现)
这篇文章主要介绍了Android自定义Spinner下拉列表(使用ArrayAdapter和自定义Adapter实现)的相关资料,需要的朋友可以参考下2015-10-10
最新评论