20.17. Capturing a Screenshot of Your View into an Image
Problem
You want to capture the contents of a view object within your app into an image and perhaps save that image to disk or perform another action with it, such as allowing the user to share it to her favorite social media network (see Recipe 11.11).
Solution
Follow these steps:
Use the
UIGraphicsBeginImageContextWithOptionsfunction to create a new image context. This new context will become the current context that subsequent painting will happen on.Invoke the
drawViewHierarchyInRect:method of yourUIViewand, as a parameter to this method, pass the boundaries of the view that you want drawn into the current context.Invoke the
UIGraphicsGetImageFromCurrentImageContextmethod, whose return value is an image representation of the current context. This is an image of typeUIImage.Convert your image instance into data using the
UIImagePNGRepresentationfunction. This function will give you an object of typeNSData.Last but not least, issue the
writeToUrl:atomically:instance method of your data object to write the image data to a location on disk, if that’s what you wish to do. Alternatively, you can perform any type of operation that you want with the image once you have it as an instance ofUIImage.
Discussion
Sometimes, programmers need to take a screenshot of the device’s screen, programmatically. One use case is when you’ve written a drawing app and you would like the user to be able to save her drawing into a file, perhaps ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access