Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Graphics screenshot without hidden items

I'm using Core Graphics to take a screenshot of my UIView, and then place it on top of that View (so I can animate it later):

// Get the screen shot
UIGraphicsBeginImageContextWithOptions(target.bounds.size, YES, [[UIScreen mainScreen] scale]);
[target.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIImageView * ss = [[UIImageView alloc] initWithImage:image];

// Add it to the View
[overlay addSubview:ss];
[target addSubview:overlay];

The problem: my UIView target has some invisible items on it (I tried both alpha = 0 and hidden = YES on them). These invisible items are appearing in the screenshot.

How can I take a screenshot without these invisible items appearing?

UPDATE: I tried using the code in Technical Q&A QA1703: Screen Capture in UIKit Applications, which also present the same issue.

UPDATE #2: It appears that the issue occurs with views that have CATransform3D applied. In another parent view that has 3D subviews, when this screenshot is taken the 3D effect is removed from the views and they appear flat (2D).

like image 221
Aaron Brager Avatar asked May 29 '26 01:05

Aaron Brager


1 Answers

Why don't you remove the hidden view from its superview. Then it will not appear on the screenshot.

[hiddenView removeFromSuperview];

EDIT:

If you don't know what subviews are hidden you can check it. The following code will remove all hidden subviews from a view and add them back.

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(UIView *subView, NSDictionary *bindings) {
    return subView.hidden;
}];

NSArray *hiddenViews = [[myView subviews] filteredArrayUsingPredicate: predicate];

for (UIView *subView in hiddenViews) {
    [subView removeFromSuperview];
}

//take your screenshot here

for (UIView *subView in hiddenViews) {
    [myView addSubview:subView];
}

EDIT2: As Duncan C pointed out, this will not work for nested subviews. You would need a recursive method for this.

like image 65
Adam Avatar answered Jun 01 '26 00:06

Adam