这个问题已经被问过很多次,比如Android 绘图、擦除和撤消操作, 但没有人给出正确的解决方案。我正在制作一个绘图应用程序,一切正常,直到我添加了撤消功能。添加撤消功能橡皮擦后无法正常工作。它使以前的绘图变黑并且也不会擦除。这是我的 DrawingView 类的构造函数:
public DrawingView(Context context){
super(context);
// if(!isInEditMode())
setLayerType(View.LAYER_TYPE_SOFTWARE, drawPaint);
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(35);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
这是 onDraw 方法
@Override
protected void onDraw(Canvas canvas) {
//draw view
// canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
for (Path p : paths)
{
drawPaint.setColor(colorsMap.get(p));
drawPaint.setStrokeWidth(widthMap.get(p));
canvas.drawPath(p, drawPaint);
}
drawPaint.setColor(paintColor);
drawPaint.setStrokeWidth(30);
if(erase){
return;
}
canvas.drawPath(drawPath, drawPaint);
}
这是touchEvent Handler
@Override
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
float touchX = event.getX();
float touchY = event.getY();
if(erase){
// drawPaint.setColor(paintColor);
drawCanvas.drawPath(drawPath, drawPaint);
invalidate();
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
undonePaths.clear();
drawPath.reset();
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawCanvas.drawPath(drawPath, drawPaint);
if(!erase){
paths.add(drawPath);
colorsMap.put(drawPath,getDrawingColor());
widthMap.put(drawPath,30);
}
drawPath = new Path();
break;
default:
return false;
}
invalidate();
return true;
}
这是我的 SetErase 方法
public void setErase(boolean isErase){
//set erase true or false
erase=isErase;
if(erase){
drawPaint.setMaskFilter(null);
drawPaint.setAlpha(0xFF);
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
else{ drawPaint.setXfermode(null);
}
}
最后我的撤消方法
public void onClickUndo()
{
if (paths.size()>0)
{
undonePaths.add(paths.remove(paths.size()-1));
invalidate();
}
else Toast.makeText(getContext(), "nothing more to undo", Toast.LENGTH_SHORT).show();
}
有没有办法在绘图应用程序中同时实现撤消和擦除功能?如果是?那么请提供一些帮助。谢谢