How to Take Screenshots Programmatically?

Goran on

blog-screenshot-featured-image

Today I’ve been playing a bit Jetpack Joyride, game is really cool and I noticed one nice detail in game: as you finish game you get option to take a look at gameplay screenshot and if you like it you can save it to your photo album. This gave me an idea to write a blog how to take screenshot programmatically and how to save this image in user photo album.

Open some existing project or create new project and place some content on screen, when you take screenshot you’ll see this content on image. You can also place some UIButton on screen and define IBAction for taking screenshot.

Add QuartzCore framework to your project:

and import QuartzCore header file:

#import <QuartzCore/QuartzCore.h>

Taking screenshot is done in few simple steps: you need to create new image context, retrieve current graphics context, render view into this context and create UIImage out of it. This UIImage we’ll save in photo album:

// create new image context
UIGraphicsBeginImageContext(self.view.bounds.size);
// retrieve the current graphics context
 CGContextRef context = UIGraphicsGetCurrentContext();
// render view into context
 [self.view.layer renderInContext:context];
// create image from context
 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
// save image to photo album
 UIImageWriteToSavedPhotosAlbum(image,
 self,
 @selector(image:didFinishSavingWithError:contextInfo:),
 NULL);

UIImageWriteToSavedPhotosAlbum function have completion selector defined, that way we’ll know was image saved successfully or some error occurred:

- (void)image:(UIImage*)image
 didFinishSavingWithError:(NSError*)error
 contextInfo:(void*)contextInfo
 {
 if (error == nil)
 NSLog(@"Image saved successfully.");
 else
 NSLog(@"Error occurred:%@",[error localizedDescription]);
 }

Thanks for reading!

3 comments
  1. FFA on:

    Very clear codes and I got it the QuartzCore it’s very useful.
    Thank you

    • Mogolodi on:

      great tutorial, but how would i have the atmoaniin finish and leave the last image in the atmoaniin sequence show. example: if i had a hidden title bar scroll out across the view and stay there.

  2. Aditya on:

    When you say title bar I am assuming you are talinkg about a UINavigationBar. If that is the case I don’t think this tutorial is a good example of what you want to do. Since UINavigationBar inherits from UIView you can get it’s frame and animate that itself without the mess of this technique.I’ve thrown together a simple tutorial to demonstrate, I think this will work better for you.

Leave Your Comment

You’re more than welcome to leave your own comment!

Just please, pretty please: don’t spam. Thank you :)