Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture screenshot of UIWebview with all the content?

I am able to capture the screen shot of the entire webpage (including the off screen content). This is working fine on simulator, but on device it is crashing. Please help me on this, check the code below (browserView is the UIWebview).

UIImage *screenImage=[[UIImage alloc] init];
UIScrollView *browserScrollableView=[[UIScrollView alloc] init];
browserScrollableView=browserView.scrollView;   
UIGraphicsBeginImageContext(browserScrollableView.contentSize);
CGPoint savedContentOffset = browserScrollableView.contentOffset;
CGRect savedFrame = browserScrollableView.frame;

browserScrollableView.contentOffset = CGPointZero;
browserScrollableView.frame = CGRectMake(0, 0, browserScrollableView.contentSize.width, browserScrollableView.contentSize.height);

[browserScrollableView.layer renderInContext: UIGraphicsGetCurrentContext()];     
screenImage = UIGraphicsGetImageFromCurrentImageContext();

browserScrollableView.contentOffset = savedContentOffset;
browserScrollableView.frame = savedFrame;
UIGraphicsEndImageContext();

NSLog(@"Captured image size is %f X %f",screenImage.size.width,screenImage.size.height);

UIImageWriteToSavedPhotosAlbum(screenImage, nil, nil, nil);
like image 880
Anil Kumar Avatar asked Apr 19 '12 09:04

Anil Kumar


1 Answers

+ (UIImage*) captureWebView: (UIWebView*)webView {
    // capture webview
    UIImage *img = nil;
    UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, webView.scrollView.opaque, 0.0);
    {
        CGPoint savedContentOffset = webView.scrollView.contentOffset;
        CGRect savedFrame = webView.scrollView.frame;

        webView.scrollView.contentOffset = CGPointZero;
        webView.scrollView.frame = CGRectMake(0, 0, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height);
        [webView.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        img = UIGraphicsGetImageFromCurrentImageContext();

        webView.scrollView.contentOffset = savedContentOffset;
        webView.scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    return img;
}
like image 199
zeeawan Avatar answered Nov 07 '22 10:11

zeeawan