使用双缓冲技术实现Android画板应用


什么是双缓冲技术?双缓冲技术就是当用户操作界面完成后,会有一个缓冲区保存用户操作的结果。

为什么要使用双缓冲技术?拿Android 游戏开发来说,界面贞每次都是全部重画的,也就说画了新的,旧的就没了,所以需要使用双缓冲技术保存之前的内容。

如何实现双缓冲?使用一个Bitmap对象保留之前的画布即可。

  1. package com.example.phonegaptest;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Bitmap;  
  5. import android.graphics.Bitmap.Config;  
  6. import android.graphics.Canvas;  
  7. import android.graphics.Color;  
  8. import android.graphics.Paint;  
  9. import android.graphics.Path;  
  10. import android.util.AttributeSet;  
  11. import android.view.MotionEvent;  
  12. import android.view.View;  
  13.   
  14. public class DrawView extends View {  
  15.     float preX;  
  16.     float preY;  
  17.     private Path path;  
  18.     public Paint paint = null;  
  19.     final int VIEW_WIDTH = 320;  
  20.     final int VIEW_HEIGHT = 480;  
  21.     Bitmap cacheBitmap = null;  
  22.     Canvas cacheCanvas = null;  
  23.   
  24.     public DrawView(Context context, AttributeSet set) {  
  25.         super(context, set);  
  26.         cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH, VIEW_HEIGHT,  
  27.                 Config.ARGB_8888);  
  28.         cacheCanvas = new Canvas();  
  29.   
  30.         path = new Path();  
  31.         cacheCanvas.setBitmap(cacheBitmap);  
  32.   
  33.         paint = new Paint(Paint.DITHER_FLAG);  
  34.         paint.setColor(Color.RED);  
  35.         paint.setStyle(Paint.Style.STROKE);  
  36.         paint.setStrokeWidth(1);  
  37.         paint.setAntiAlias(true);  
  38.         paint.setDither(true);  
  39.     }  
  40.   
  41.     @Override  
  42.     public boolean onTouchEvent(MotionEvent event) {  
  43.         float x = event.getX();  
  44.         float y = event.getY();  
  45.   
  46.         switch (event.getAction()) {  
  47.         case MotionEvent.ACTION_DOWN:  
  48.             path.moveTo(x, y);  
  49.             preX = x;  
  50.             preY = y;  
  51.             break;  
  52.         case MotionEvent.ACTION_MOVE:  
  53.             path.quadTo(preX, preY, x, y);  
  54.             preX = x;  
  55.             preY = y;  
  56.             break;  
  57.         case MotionEvent.ACTION_UP:  
  58.             cacheCanvas.drawPath(path, paint);  
  59.             path.reset();  
  60.             break;  
  61.         }  
  62.         invalidate();  
  63.         return true;  
  64.     }  
  65.   
  66.     @Override  
  67.     protected void onDraw(Canvas canvas) {  
  68.         super.onDraw(canvas);  
  69.         Paint bmpPaint = new Paint();  
  70.         canvas.drawBitmap(cacheBitmap, 00, bmpPaint);  
  71.         canvas.drawPath(path, paint);  
  72.     }  
  73.   
  74. }  

相关内容