How to use NSUndoManager with a UIImageView or CGContext

痞子三分冷 提交于 2019-12-05 18:23:58

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!