android canvas remove previous path being drawn
I think the easiest way for doing that is having 2 bitmaps (1 additional backup bitmap for restoring previous state).
You need to save previous state of a bitmap before you start new drawings.
Here is how I would modify your code:
private HashMap<Integer, Path> pathMap; // current Paths being drawn
private HashMap<Integer, Point> previousPointMap; // current Points
private Bitmap bitmap; // drawing area for display or saving
private Bitmap bitmapBackup;
private Canvas bitmapCanvas; // used to draw on bitmap
private Canvas bitmapBackupCanvas;
// remember last bitmap before new drawings...
private void touchStarted()
{
bitmapBackupCanvas.drawBitmap(bitmap, 0, 0, null);
}
// called when the user finishes a touch
private void touchEnded(int lineID)
{
Path path = pathMap.get(lineID); // get the corresponding Path
bitmapCanvas.drawPath(path, paintLine); // draw to bitmapCanvas
path.reset(); // reset the Path
rememberLineId = lineID;
} // end method touch_ended
//undo
private void undo()
{
Path path = pathMap.get(rememberLineId); // get the corresponding Path
pathMap.remove(rememberLineId);
bitmapCanvas.drawBitmap(bitmapBackup, 0, 0, null); // restore from backup
path.reset(); // reset the Path
}
It is an old post, but I was looking for an answer for that issue as well. I was not satisfied with the chosen answer for that post and I found one myself after that. I actually think that having a full bitmap as a backup is not great memory-wise and it will limit the number of undo steps we can have.
I believe a better solution would be :
To have a stack of paths in your class
private Stack<Path> m_pathHistory = new Stack<Path>();
next to your canvas and your paintbrush (initialization skipped) :
private Canvas m_drawingCanvas;
private Paint m_paint;
Then every time a stroke is finished (on the touch up event), add a "clone" of the path to the undo history:
m_pathHistory.Push(new Path(currentPath));
And here is the undo function :
public void Undo()
{
if(m_pathHistory.Count > 0)
{
m_pathHistory.Pop(); // Remove the last path from the history
m_drawingCanvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear); // Clear the canvas with a transparent color
// Draw the paths which are still in the history
foreach (Path p in m_pathHistory)
{
m_drawingCanvas.DrawPath(p, m_paint);
}
}
}
The paths are much smaller to store in the memory than the full bitmaps, so we can have a much bigger history.