當數據量很大時,繪圖可能需要幾秒鐘甚至更長的時間,而且有時還會出現閃爍現象,爲了解決這些問題,可採用雙緩衝技術來繪圖。
雙緩衝即在內存中創建一個與屏幕繪圖區域一致的對象,先將圖形繪製到內存中的這個對象上,再一次性將這個對象上的圖形拷貝到屏幕上,這樣能大大加快繪圖的速度。雙緩衝實現過程如下:
1、在內存中創建與畫布一致的緩衝區
2、在緩衝區畫圖
3、將緩衝區位圖拷貝到當前畫布上
4、釋放內存緩衝區
下面的例子(一個畫圖板)將實現雙緩衝畫圖
先自定義一個View(Bitmap將會繪製到這個View上)
這裏主要理解:一些基本的原理,詳細看代碼註釋
public class DoubleBitmap extends View {
private Bitmap mCachBitMap;//緩衝畫布
private Canvas mCanvas;//畫圖
private Paint mPaint;//畫布
private Path mPath;
private int x,y,dx,dy;
public DoubleBitmap(Context context) {
this(context, null);
}
public DoubleBitmap(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint=new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(3);
mPaint.setColor(Color.RED);
mPaint.setAntiAlias(true);
mPath=new Path();
}
//監聽view的大小變化,間接去調用OnMeasure(),onLayout()
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);//先測量過後才能獲取View的寬和高
mCachBitMap= Bitmap.createBitmap(getMeasuredWidth(),getMeasuredHeight(), Bitmap.Config.ARGB_8888);
mCanvas=new Canvas(mCachBitMap);//把緩衝畫布綁定到新創建的canvas對象上面去
}
@Override
public boolean onTouchEvent(MotionEvent event) {
x=(int)event.getX();
y=(int)event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
dx=x;
dy=y;
mPath.moveTo(dx,dy);
break;
case MotionEvent.ACTION_MOVE:
mPath.quadTo(dx,dy,x,y);//繪製二階貝塞爾曲線
dx=x;
dy=y;
break;
case MotionEvent.ACTION_UP:
mCanvas.drawPath(mPath, mPaint);//用自定義的cavas對象繪製path
mPath.reset();//path重置
break;
}
invalidate();//時刻準備重繪
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mCachBitMap,0,0,mPaint);//把緩存畫布上的內容繪製到View默認畫布上面去 一次性拷貝過來,避免屏幕閃爍
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
}