O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

  1. Use the UIGraphicsBeginImageContextWithOptions function to create a new image context. This new context will become the current context that subsequent painting will happen on.

  2. Invoke the drawViewHierarchyInRect: method of your UIView and, as a parameter to this method, pass the boundaries of the view that you want drawn into the current context.

  3. Invoke the UIGraphicsGetImageFromCurrentImageContext method, whose return value is an image representation of the current context. This is an image of type UIImage.

  4. Convert your image instance into data using the UIImagePNGRepresentation function. This function will give you an object of type NSData.

  5. 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 of UIImage.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required