效果圖:
View代碼:activity裡設置顯示該view即可
- package com.tszy.view;
-
- 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.view.MotionEvent;
- import android.view.View;
-
- /**
- * 雙緩沖區繪圖demo 手寫板
- *
- * @author JianbinZhu
- *
- */
- public class View7 extends View {
- private Paint paint;
- private Canvas cacheCanvas;
- private Bitmap cachebBitmap;
- private Path path;
-
- public View7(Context context) {
- super(context);
- // TODO Auto-generated constructor stub
- paint = new Paint();
- paint.setAntiAlias(true);
- paint.setStrokeWidth(3);
- paint.setStyle(Paint.Style.STROKE);
- paint.setColor(Color.CYAN);
-
- path = new Path();
- cachebBitmap = Bitmap.createBitmap(480, 320, Config.ARGB_8888);
- cacheCanvas = new Canvas(cachebBitmap);
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- canvas.drawColor(Color.BLACK);
-
- //繪制上一次的,否則不連貫
- canvas.drawBitmap(cachebBitmap, 0, 0, null);
- canvas.drawPath(path, paint);
- }
-
- private float cur_x, cur_y;
- private boolean isMoving;
- @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 : {
- cur_x = x;
- cur_y = y;
- path.moveTo(cur_x, cur_y);
- isMoving = true;
- break;
- }
-
- case MotionEvent.ACTION_MOVE : {
- // 二次曲線方式繪制
- path.quadTo(cur_x, cur_y, x, y);
- // 下面這個方法貌似跟上面一樣
- // path.lineTo(x, y);
- cur_x = x;
- cur_y = y;
- break;
- }
-
- case MotionEvent.ACTION_UP : {
- // 鼠標彈起保存最後狀態
- cacheCanvas.drawPath(path, paint);
- path.reset();
- isMoving = false;
- break;
- }
- }
-
- // 刷新界面
- invalidate();
-
- return true;
- }
- }