我正在使用 Core Graphics 截取我的 UIView 的屏幕截图,然后将它放在该 View 的顶部(这样我可以稍后为其制作动画):
// 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];
问题:我的 UIView target
上有一些不可见的项目(我对它们尝试了 alpha = 0
和 hidden = YES
) .这些不可见的项目出现在屏幕截图中。
如何截屏而不显示这些不可见的项目?
更新:我尝试使用 Technical Q&A QA1703: Screen Capture in UIKit Applications 中的代码, 这也存在同样的问题。
更新 #2: 问题似乎出现在应用了 CATransform3D 的 View 中。在另一个具有 3D subview 的父 View 中,当截取此屏幕截图时,3D 效果从 View 中移除并且它们显示为平面 (2D)。
最佳答案
为什么不从其父 View 中删除隐藏 View 。然后它不会出现在屏幕截图上。
[hiddenView removeFromSuperview];
编辑:
如果您不知道隐藏了哪些 subview ,您可以检查一下。以下代码将从 View 中删除所有隐藏的 subview 并将它们添加回来。
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:正如 Duncan C 所指出的,这不适用于嵌套 subview 。为此,您需要一个递归方法。
关于objective-c - 没有隐藏项目的 Core Graphics 屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287510/