Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Last active December 3, 2020 11:40
Show Gist options
  • Save brennanMKE/10010625 to your computer and use it in GitHub Desktop.
Save brennanMKE/10010625 to your computer and use it in GitHub Desktop.
Screenshot of a view excluding views
- (UIImage *)screenshotOfView:(UIView *)view excludingViews:(NSArray *)excludedViews {
if (!floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
NSCAssert(FALSE, @"iOS 7 or later is required.");
}
// hide all excluded views before capturing screen and keep initial value
NSMutableArray *hiddenValues = [@[] mutableCopy];
for (NSUInteger index=0;index<excludedViews.count;index++) {
[hiddenValues addObject:[NSNumber numberWithBool:((UIView *)excludedViews[index]).hidden]];
((UIView *)excludedViews[index]).hidden = TRUE;
}
UIImage *image = nil;
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// reset hidden values
for (NSUInteger index=0;index<excludedViews.count;index++) {
((UIView *)excludedViews[index]).hidden = [[hiddenValues objectAtIndex:index] boolValue];
}
// clean up
hiddenValues = nil;
return image;
}
@matt-curtis
Copy link

@rakeshta This happens because afterScreenUpdates makes the UI update immediately, instead of waiting until the end of the run loop. Looking for a solution to this now :/

@Kmohamed
Copy link

There's a weird issue on iPhone 7 simulator and Device it does not work with UIWindow.
If I exclude all subview of UIWindow the image will not be black but it works on iPhone 6 , 6s .....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment