8

我正在尝试从笔尖加载视图,对其进行配置并对其进行快照,而不将其添加到屏幕上:

+ (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 和复合材料的大小都正确但空白。如何从从笔尖加载的视图创建 UIImage,而不将视图添加到屏幕?

4

3 回答 3

3

前段时间我遇到了类似的问题,据我所知,不可能拍摄视图的快照,这实际上不在屏幕上。我创建了一个解决方法并将我想要快照的相关视图放置在当前 ViewControllers 视图边界之外,这样您就不会看到它。在这种情况下,可以创建有效的快照。希望这可以帮助 :)

于 2015-02-16T23:46:33.963 回答
2

这感觉有点hacky,但我试过了,它确实完成了工作。如果您从主视图后面的 nib 加载视图,则可以只截取该层的屏幕截图。只要它不是内存密集型视图,用户就永远不会知道该视图已添加到超级视图中。

UIGraphicsBeginImageContext(CGSizeMake(catView.frame.size.width, catView.frame.size.height));
CGContextRef context = UIGraphicsGetCurrentContext();
[catView.layer renderInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

因此,在将 nib 加载到主视图后面后运行此代码。加载后,您可以使用 `[catView removeFromSuperiew]' 将其删除

于 2015-02-16T23:40:02.083 回答
0
    UIGraphicsBeginImageContext(view.frame.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
于 2015-02-23T12:49:53.040 回答