how to take a screenshot of the iPhone programmatically?

The previous code assumes that the view to be captured lives on the main screen…it might not.

Would this work to always capture the content of the main window? (warning: compiled in StackOverflow)


- (UIImage *) captureScreen {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Leave a Comment