2013.4.15 双缓冲技术

来源:互联网 发布:经济学博士就业 知乎 编辑:程序博客网 时间:2024/05/03 12:27

主要原理:当一个动画争先显示时,程序有在改变他,前面还没有显示完,程序又请求重新绘制,这样屏幕就会不停的闪烁。为了避免闪烁,可以用双缓冲技术,将要哦处理的图片都在内存中处理好之后,再将其显示到屏幕上。这样显示出来的总是完整的图像,不会出现闪烁的现象。

核心技术:先通过setBitmap方法将要绘制哦所有图形绘制到一个Bitmap上,然后在来调用drawBitmap方法绘制出这个Bitmap,显示在屏幕上。

ex:  

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.view.MotionEvent;
import android.view.View;


public class GameView extends View implements Runnable{
/*声明Bitmap对象
**/
Bitmap mBitQQ=null;
Paint mpaint=null;
/*create teh buffer*/
Bitmap mSCBitmap=null;
/*create Canvas*/
Canvas mCanvas=null;




public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
/*load the resource*/
mBitQQ=((BitmapDrawable)getResources().getDrawable(R.drawable.yhzx)).getBitmap();
//create the buffer of screen
mSCBitmap=Bitmap.createBitmap(320,480,Config.ARGB_8888);
//create the canvas
mCanvas=new Canvas();
//put the content of draw in teh mSCBitmap
mCanvas.setBitmap(mSCBitmap);

mpaint=new Paint();
//将mBitQQ绘制到mSCBitmap上
mCanvas.drawBitmap(mBitQQ,0,0,mpaint);

//open teh thread
new Thread(this).start();
}


@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//将mSCBitmap显示到屏幕上
canvas.drawBitmap(mSCBitmap, 0, 0,mpaint);
}


@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return true;
}


@Override
public void run() {
// TODO Auto-generated method stub
while(!Thread.currentThread().isInterrupted()){
try{
Thread.sleep(100);
}catch(InterruptedException e){
Thread.currentThread().interrupted();
}
postInvalidate();
}
}


}

原创粉丝点击