问题
I have an app that uses cgcontext to draw things onto a UIImageView that the user draws using touch events, and I want to be able to undo the drawings made by the user.
Edit:
I am trying to use my touchesBegan to save theUIImage at the begining of a touch to the NSUndoManager
And then how do I use it to undo using a UIAlertView.
Meaning, I want to call a method from my UIAlertView that undo's then another that will redo, but I don't know how to accomplish this.
Please help
回答1:
I write graphics software for the iPhone (http://www.layersforiphone.com/) and I spent a while trying to figure this out. The problem is, CGContexts aren't inherently "undoable." You can't unfill a rectangle or restore a portion you've drawn over. The data just isn't there. In my experience, the best bet is to create a "save" method that looks at the region being altered and saves the image data in that region to the undo stack before drawing operations are performed. Then, when you decide to undo, you can take the modified region and restore it from your saved data.
I chose to implement that approach independently of NSUndoManager in Layers because you basically need a stack of CGImageRefs and CGRects and it doesn't map well to the NSUndoManager.
Note: Technically, you could just save a copy of the entire image each time it is modified. This is a bad use of memory, though - since you may change only a small area. If you want to have a generous undo history (10+ steps), it's definitely worth your while to save and restore small subimages within your drawing space.
Hope that helps! I know it's not a great solution - you really can't do much with the built-in APIs. If you create a general solution to this problem I think a lot of people would be interested in it, though!
来源:https://stackoverflow.com/questions/1907715/how-to-use-nsundomanager-with-a-uiimageview-or-cgcontext