Sunday, February 26, 2017

How To: Create Undo and Redo in a Drawing App

Hi guys.

I want to share how to create undo and redo in a drawing app. I tried using NSUndoManager for this, but it doesn't work. Why? I don't know. When something don't work, I tried for a bit, and if I have no more idea to try and work it out, I simply abandon the idea and try something else totally. There is no point lingering on something that you simply do not know.

The way to implement undo and redo is quite simple really. You just detect user's end stroke, and then save that drawn image into a MutableArray. This will eat memory a bit especially if you have a very big image. Alternatively you can simply store the drawn image in the TMP folder of your app sandbox use names like "undo0.png, undo1.png, undo2.png...". Have a global undo index variable to keep track of the undo/redo steps. When undoing, you -1 to the index, and load the image based on this index number. And when redoing, you +1 to the index, and load that image.

Something like this:


-(void)undo {
undoIndex -= 1;
NSString *imageName = [NSString stringWithFormat:@"%undold.png",undoIndex];
yourImage.image =  [self loadImageFromTMP:imageName];
}

-(void)redo {
undoIndex += 1;
NSString *imageName = [NSString stringWithFormat:@"%undold.png",undoIndex];
yourImage.image =  [self loadImageFromTMP:imageName];
}


Of course, you have to handle the undoIndex limits (>=0 and <maxUndolevel). Simple right? Kthxbai.

No comments:

Post a Comment