双缓冲技术就是当用户操作界面完成后,会有一个缓冲区保存用户操作的结果。
为什么要使用双缓冲技术?拿Android 游戏开发来说,界面贞每次都是全部重画的,也就说画了新的,旧的就没了,所以需要使用双缓冲技术保存之前的内容。
如何实现双缓冲?使用一个Bitmap对象保留之前的画布即可。
package com.example.phonegaptest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawView extends View {
float preX;
float preY;
private Path path;
public Paint paint = null;
final int VIEW_WIDTH = 320;
final int VIEW_HEIGHT = 480;
Bitmap cacheBitmap = null;
Canvas cacheCanvas = null;
public DrawView(Context context, AttributeSet set) {
super(context, set);
cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH, VIEW_HEIGHT,
Config.ARGB_8888);
cacheCanvas = new Canvas();
path = new Path();
cacheCanvas.setBitmap(cacheBitmap);
paint = new Paint(Paint.DITHER_FLAG);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setAntiAlias(true);
paint.setDither(true);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(x, y);
preX = x;
preY = y;
break;
case MotionEvent.ACTION_MOVE:
path.quadTo(preX, preY, x, y);
preX = x;
preY = y;
break;
case MotionEvent.ACTION_UP:
cacheCanvas.drawPath(path, paint);
path.reset();
break;
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint bmpPaint = new Paint();
canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint);
canvas.drawPath(path, paint);
}
}