一、创建变量
//DoodleView
private Paint mPaint = new Paint();
private List<Path> mPathList = new ArrayList<>(); // 保存涂鸦轨迹的集合
private float mLastX, mLastY;
private Path mCurrentPath; // 当前的涂鸦轨迹
private Canvas canvas;
private ImageView imageView;
private Bitmap bitmap;
二、初始化变量
void initDoodleView(){
imageView = findViewById(R.id.doodleView_container);
imageView.setOnTouchListener(this);
// 设置画笔
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(3);
mPaint.setAntiAlias(true);
mPaint.setStrokeCap(Paint.Cap.ROUND);
//创建黑色背景的bitmap
//bitmap = Bitmap.createBitmap(imageView.getWidth(),imageView.getHeight(), Bitmap.Config.RGB_565);
//获取drawable中的透明图片创建透明背景的bitmap
Bitmap bitmapT = BitmapFactory.decodeResource(getResources(),R.drawable.transparent);
//把bitmapT从坐标(0,0)开始裁剪成需要的大小
bitmap = Bitmap.createBitmap(bitmapT, 0, 0, imageView.getWidth(), imageView.getHeight());
canvas = new Canvas(bitmap);
imageView.setImageBitmap(bitmap);
}
三、在onTouch事件中添加涂鸦路径
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int x = (int)motionEvent.getX();//motionEvent.getRawX();
int y = (int)motionEvent.getY();
view.performClick();
switch(motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
mCurrentPath = new Path(); // 新的涂鸦
mPathList.add(mCurrentPath); // 添加的集合中
mCurrentPath.moveTo(motionEvent.getX(), motionEvent.getY());
mLastX = motionEvent.getX();
mLastY = motionEvent.getY();
view.invalidate(); // 刷新
break;
case MotionEvent.ACTION_UP:
mCurrentPath.quadTo(
mLastX,
mLastY,
(motionEvent.getX() + mLastX) / 2,
(motionEvent.getY() + mLastY) / 2); // 使用贝塞尔曲线 让涂鸦轨迹更圆滑
mCurrentPath = null; // 轨迹结束
view.invalidate(); // 刷新
break;
case MotionEvent.ACTION_MOVE:
mCurrentPath.quadTo(
mLastX,
mLastY,
(motionEvent.getX() + mLastX) / 2,
(motionEvent.getY() + mLastY) / 2); // 使用贝塞尔曲线 让涂鸦轨迹更圆滑
mLastX = motionEvent.getX();
mLastY = motionEvent.getY();
canvas.drawPath(mCurrentPath, mPaint);
view.invalidate(); // 刷新
break;
}
return true;
}
四、清除Imageview中的所有涂鸦
//bitmap = Bitmap.createBitmap(imageView.getWidth(),imageView.getHeight(), Bitmap.Config.RGB_565);
bitmap = Bitmap.createBitmap(bitmapT, 0, 0, imageView.getWidth(),imageView.getHeight());
canvas = new Canvas(bitmap);
if (bitmap!=null && imageView!=null)
imageView.setImageBitmap(bitmap);