Programmatically Getting a Screencapture of any UIView

    July 27th, 2009 Posted by: - posted under:Snippets


    Hey guys. This post is in response to a comment made in my last post about NSTimers. Techy asked if we could do a post on how to take screenshots programmatically using the iPhone SDK. For this minor project we will be creating a small web browser application that will start at, and have a button on a toolbar at the bottom to take a picture of the web view and save it into you photo library. Lets take a look.



    You can get the source here: Screenshot Project


    Step 1

    Create a view based application in xCode. Call it whatever.

    Step 2

    In the header for your view controller declare the following:

    @interface ScreenCaptureViewController : UIViewController
            IBOutlet UIWebView *webview;
    @property (nonatomic, retain) IBOutlet UIWebView *webview;

    Step 3

    Open up your view controller’s XIB file.

    • Drag in a UIToolbar and put it at the bottom of the screen.
    • Drag in a UIToolbarButtom and name it appropriately.
    • Drag in a flexible space holder on either side of the button to center it.
    • Drag in a UIWebView to take up the rest of the screen above the toolbar.
    • Connect the UIWebView to our webview IBOutlet.
    • Connect out UIToolbarButton to our IBAction catureScreen:(id)sender.

    Step 4

    Uncomment out the viewDidLoad method and use the following code:

    - (void)viewDidLoad
        [super viewDidLoad];
        [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];

    Step 5

    All the is left to do is create the IBAction captureScreen. This is the code for the method, place it in the main file for your view controller.

            [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
            UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
            UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);


    So that is it. You can use this general code to take a screenshot of any UIView subclass. All you need to do is replace webview.frame.size in the third line with foobar.frame.size where foobar is any UIView subclass. Hope this answered your question Techy. Happy Coding.