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的畫布將歷史數據都保存進去.android