Reputation: 8702
I've made a simple whiteboard on my Android app, where the user can draw something. I want to add an Undo feature so that he will be able to go back to his previous action.
On my Touch Start
event, I've added the following code which basically adds the current canvas to an ArrayList
and create a new one to avoid same reference.
previousDrawing.add(this.canvas);
this.canvas = new Canvas(this.bitmap);
Then, in my undo
method, I've added the following code:
if (previousDrawing.size() > 0)
{
// Remove last
this.canvas = previousDrawing.remove(previousDrawing.size() - 1);
this.canvas.setBitmap(this.bitmap);
}
It doesn't work at all. I mean, I'm able to draw on my canvas using this.canvas.drawPath(this.path, this.paint);
but not to save and restore a previous canvas.
Could you help me to do that ?
Thanks in advance.
EDIT :
I've also tryied to use the saveLayer method
. But when I save, I'm no longer able to draw on the canvas. Is this a normal behaviour ?
Upvotes: 1
Views: 2963
Reputation: 4007
Try drawBitmap
instead of setBitmap
this.canvas.drawBitmap(this.bitmap, 0, 0, null);
Edit
if (previousDrawing.size() > 0)
{
// Remove last
this.bitmap = previousDrawing.get(previousDrawing.size() - 1);
this.canvas.drawBitmap(this.bitmap, 0, 0, null);
previousDrawing.remove(previousDrawing.size() - 1);
}
Reference link
Upvotes: 3
Reputation: 10518
canvas doesnt hold pixels. Bitmap does. So it is useless to save and restore canvas. You can save and restore bitmap, but it is very memory consuming operation.
You better log user drawing actions. To go back in history you should redraw all actions from the beggining except the last one. To make it faster you can keep several key history bitmaps. Because redrawing all from the beggining is slow...
Upvotes: 0