Last active
February 14, 2020 16:24
-
-
Save dhoerl/ea583ed8e9e94a6a44e276dc2ba55390 to your computer and use it in GitHub Desktop.
Screenshot a UIView subsection in an UIImage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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