This Question has been asked many times like Android Drawing, Erasing and Undoing Action But no one has giving the proper solution for it. I am making a drawing app and everything was working fine until i added undo feature. After adding undo feature eraser is not working fine. It makes previous drawing black and don't erase as well. This is my DrawingView Class' constructor:
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);
}
Here is the onDraw method
@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);
}
and here is 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;
}
here is my SetErase method
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);
}
}
and the last my undo Method
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();
}
Is there no way to implement undo and erase features together in a drawing app? If yes? then please provide some help. Thanks