Skip to content

Instantly share code, notes, and snippets.

@dhoerl
Last active February 14, 2020 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhoerl/ea583ed8e9e94a6a44e276dc2ba55390 to your computer and use it in GitHub Desktop.
Save dhoerl/ea583ed8e9e94a6a44e276dc2ba55390 to your computer and use it in GitHub Desktop.
Screenshot a UIView subsection in an UIImage
// Inspired by https://gist.github.com/nitrag/b3117a4b6b8e89fdbc12b98029cf98f8
+ (UIImage *)imageFromView:(UIView *)view subsection:(CGRect)subRect
{
// Image will be sized to the smaller rectangle
UIGraphicsBeginImageContextWithOptions(subRect.size, YES, 0);
// The primary view needs to shift up and left so the desired rect is visible
// But the rect passed below needs to be sized to the view, otherwise the image is compressed
CGRect drawRect = CGRectMake(-subRect.origin.x, -subRect.origin.x, view.bounds.size.width, view.bounds.size.height);
[view drawViewHierarchyInRect:drawRect afterScreenUpdates:NO]; // I got compiler complaints using YES ???
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment