Programmatically take a screenshot of specific area

Sharky picture Sharky · Jan 2, 2012 · Viewed 9.5k times · Source

Like you can see in my code, I take a screenshot and save it to the photo album.

//for retina displays
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
    UIGraphicsBeginImageContext(self.view.bounds.size);
}
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

At the beginning I used webview.size instead of self.view.bounds.size and it was working properly because the view was located at 0/0. But now I centered the WebView but the pictures is starts at 0/0 for the given size.

How can I configure that the screenshot starts at another location (e.g. 300/150) for the given size?

Or is there another way to take a picture of an UIWebView?

Answer

escrafford picture escrafford · Mar 8, 2013

You need to make two changes in order to only grab a portion of the screen:

  1. Create a smaller image - use the size of the rect you'd like to capture.
  2. Move the origin of the context that you're rendering into to be negative x/y of the rect you'd like to capture.

After that, you just render the layer into the context as you were doing, and you should get what you're looking for. Something like this ought to do it:

CGRect grabRect = CGRectMake(40,40,300,200);

//for retina displays
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(grabRect.size, NO, [UIScreen mainScreen].scale);
} else {
    UIGraphicsBeginImageContext(grabRect.size);
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, -grabRect.origin.x, -grabRect.origin.y);
[self.view.layer renderInContext:ctx];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);