我试图从笔尖加载视图,配置它并拍摄快照,而不将其添加到屏幕上:
+ (void)composeFromNibWithImage:(UIImage*)catImage completion:(CompletionBlock)completion {
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"CatNib" owner:nil options:nil];
CatView *catView = [nibContents firstObject];
//here, catView is the correct size from the nib, but is blank if inspected with the debugger
catView.catImageView.image = catImage;
catView.furButton.selected = YES;
UIImage *composite = [UIImage snapshot:catView];
completion(composite);
}
快照是典型的:
+ (UIImage *)snapshot:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
但是,当我单步执行代码时,catView和composite都会正确调整大小但是空白。如何从一个从笔尖加载的视图创建UIImage,而不将视图添加到屏幕?
答案 0 :(得分:3)
前段时间我遇到了类似的问题,据我所知,无法拍摄视图的快照,实际上屏幕上并没有 。我创建了一个解决方法,并在当前的ViewControllers视图边界之外放置了我想要快照的相关视图,以便您不会看到它。在这种情况下,可以创建有效的快照。希望这会有所帮助:)
答案 1 :(得分:1)
这感觉有点hacky,但我尝试了它,它确实完成了工作。如果从主视图后面的笔尖加载视图,则可以截取该图层的屏幕截图。只要它不是内存密集型视图,用户就永远不会知道该视图已添加到超级视图中。
UIGraphicsBeginImageContext(CGSizeMake(catView.frame.size.width, catView.frame.size.height));
CGContextRef context = UIGraphicsGetCurrentContext();
[catView.layer renderInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
在您的主视图后面加载nib后运行此代码。一旦加载,您可以使用`[catView removeFromSuperiew]'
删除它答案 2 :(得分:0)
UIGraphicsBeginImageContext(view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();