1、最近公司项目有个需求是要做草稿纸功能,花了点时间完成了这个功能,顺便自己记录一下
2、大体思路是用画笔对按下和移动的路径进行描边,然后画出,抬起之后保存这个路径和画笔,以供后期要删除使用
3、下面上代码
//初始化画笔
private void init(Context context) {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
//画笔是空心的
mPaint.setStyle(Paint.Style.STROKE);
//画笔的笔尖 这里是圆形
mPaint.setStrokeCap(Paint.Cap.ROUND);
// Join.MITER(结合处为锐角)
// Join.Round(结合处为圆弧)
// Join.BEVEL(结合处为直线)
mPaint.setStrokeJoin(Paint.Join.ROUND);
//处理图片
mPaint.setFilterBitmap(true);
//设置画笔的宽度
mPaint.setStrokeWidth(5);
//设置画笔颜色
mPaint.setColor(Color.BLACK);
}
...
//取消撤回功能
public void redo() {
int size = mRemoveList == null ? 0 : mRemoveList.size();
if (size > 0) {
DrawInfo info = mRemoveList.remove(size - 1);
mDrawList.add(info);
reDraw();
}
}
//撤回
public void undo() {
int size = mDrawList == null ? 0 : mDrawList.size();
if (size > 0) {
DrawInfo info = mDrawList.remove(size - 1);
mRemoveList.add(info);
reDraw();
}
}
//清除
public void clear() {
if (mDrawList != null && mRemoveList != null) {
mRemoveList.clear();
mDrawList.clear();
if (mBufferBitmap != null) {
mBufferBitmap.eraseColor(Color.TRANSPARENT);
invalidate();
}
}
}
//重新绘制
private void reDraw() {
if (mDrawList != null) {
//把原来绘制在bitmap上的痕迹全部设置为透明,类似擦除
mBufferBitmap.eraseColor(Color.TRANSPARENT);
for (DrawInfo drawInfo : mDrawList) {
//对mDrawList集合中的元素重新画上去
drawInfo.draw(mBufferCanvas);
}
invalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// PointF midPoint = getMidPointOfFinger(event);
int action = event.getAction() & MotionEvent.ACTION_MASK;
float x = event.getX();
float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
mCanDrag = false;
DownX = x;
DownY = y;
if (mPath == null) {
mPath = new Path();
}
mPath.moveTo(x, y);
break;
case MotionEvent.ACTION_MOVE:
// if (mCanDrag) {
// x = event.getX();
// y = event.getY();
// float dx = x - DownX;
// float dy = y - DownY;
// mBufferMatrix.preTranslate((float) (dx * 0.05), (float) (dy * 0.05));
// invalidate();
// return true;
// }
mPath.quadTo(DownX, DownY, (x + DownX) / 2, (y + DownY) / 2);
if (mBufferBitmap == null) {
initBuffer();
}
mBufferCanvas.drawPath(mPath, mPaint);
invalidate();
DownX = x;
DownY = y;
break;
case MotionEvent.ACTION_UP:
DownX = x;
DownY = y;
saveDraw();
mPath.reset();
break;
// case MotionEvent.ACTION_POINTER_DOWN:
return true;
}
//清除
public void clear() {
if (mDrawList != null && mRemoveList != null) {
mRemoveList.clear();
mDrawList.clear();
if (mBufferBitmap != null) {
mBufferBitmap.eraseColor(Color.TRANSPARENT);
invalidate();
}
}
}
核心代码就这些了 画板功能还是比较简单的