Skip to content

Instantly share code, notes, and snippets.

@psobko
Last active December 10, 2015 07:38
Show Gist options
  • Save psobko/4402753 to your computer and use it in GitHub Desktop.
Save psobko/4402753 to your computer and use it in GitHub Desktop.
Take a screenshot of a given view and optionally crop it.
+(UIImage*)TakeScreenshotOfView:(UIView*)view Cropping:(CGRect)dimensions
{
CGFloat scale = 1.0f;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
scale = [[UIScreen mainScreen] scale];
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
CGRect rect = CGRectMake(dimensions.origin.x , dimensions.origin.y * scale , dimensions.size.width * scale, dimensions.size.height * scale);
CGImageRef croppedImageRef = CGImageCreateWithImageInRect([fullImage CGImage], rect);
UIGraphicsEndImageContext();
UIImage *croppedImage = [UIImage imageWithCGImage:croppedImageRef];
return croppedImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment