Quick Tip: Take Screenshots Programmatically

In today’s quick tip I will show you how to take screenshots from your iOS app programmatically. There are several ways to do it, so I will show you the code Apple provided with the last SDK update.

To take screenshots, you will need to add the Quartz Core framework to your project. In the MyProject.xcodeproj file, under the Summary tab, scroll down to Linked Libraries and Frameworks and click on the plus button. Select QuartzCore.framework, and click Add.

Add this code wherever you want to take the screenshot:

CGSize imageSize = self.bounds.size;
if (NULL != UIGraphicsBeginImageContextWithOptions)
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
else
    UIGraphicsBeginImageContext(imageSize);
   
CGContextRef context = UIGraphicsGetCurrentContext();
   
// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
    if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
    {
        // -renderInContext: renders in the coordinate space of the layer,
        // so we must first apply the layer's geometry to the graphics context
        CGContextSaveGState(context);
        // Center the context around the window's anchor point
        CGContextTranslateCTM(context, [window center].x, [window center].y);
        // Apply the window's transform about the anchor point
        CGContextConcatCTM(context, [window transform]);
        // Offset by the portion of the bounds left of and above the anchor point
        CGContextTranslateCTM(context,
                              -[window bounds].size.width * [[window layer] anchorPoint].x,
                              -[window bounds].size.height * [[window layer] anchorPoint].y);
           
        // Render the layer hierarchy to the current context
        [[window layer] renderInContext:context];
           
        // Restore the context
        CGContextRestoreGState(context);
    }
}

/ Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   
UIGraphicsEndImageContext();
 
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

This will take a screenshot and save it to the Photos Album. You can change the size in the first line of code if you only want to take a screenshot of a certain part of the screen.

Conclusion

With this code, you will be able to take screenshots of your app programmatically. Try it out and let me know if you have any doubts with the code or have any problem while running it!

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

Your email address will not be published. Required fields are marked *