package com.example.test33; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawView extends View { Paint paint; Canvas cacheCanvas; Bitmap cacheBitmap; Path path; public DrawView(Context context) { super(context); // TODO Auto-generated constructor stub this.initDrawView(); } public DrawView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub this.initDrawView(); } public DrawView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // TODO Auto-generated constructor stub this.initDrawView(); } private void initDrawView(){ cacheBitmap = Bitmap.createBitmap(720, 1280, Config.ARGB_8888); cacheCanvas = new Canvas(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); path = new Path(); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.drawBitmap(cacheBitmap, 0, 0, paint); canvas.drawPath(path, paint); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: path.moveTo(x, y); break; case MotionEvent.ACTION_MOVE: path.lineTo(x, y); break; case MotionEvent.ACTION_UP: cacheCanvas.drawPath(path, paint); path.reset(); break; default: break; } this.invalidate(); return true; } }
1级缓冲是将一次按下拖动抬起手指的绘画动作存储在path中, 动作结束后绘制到屏幕, 2级缓冲是利用绑定了bitmap的画布将历史数据都保存进去.