I am writing graphics software for the iPhone ( http://www.layersforiphone.com/ ) and I spent some time trying to figure it out. The problem is that CGContexts are not inherently βexcellentβ. You cannot fill the rectangle or restore the part that you drew. There is simply no data. In my experience, itβs best to create a βsaveβ method that looks at the changed region and saves the image data in that region onto the undo stack before drawing operations are performed. Then, when you decide to cancel, you can take the changed area and restore it from the saved data.
I decided to implement this approach independently of NSUndoManager in layers, because you basically need a stack of CGImageRefs and CGRects, and it does not render NSUndoManager well.
Note. Technically, you can simply save a copy of the entire image each time it is resized. This is a poor use of memory, though - since you can only change a small area. If you want to have a generous cancellation history (more than 10 steps), you should definitely save and restore small subimases in your drawing space.
Hope this helps! I know this is not a great solution - you really can't do much with the built-in APIs. If you create a common solution to this problem, I think many people will be interested in this, though!
source share