Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 拍摄视图快照,而不将其添加到屏幕_Ios_Uiview_Uiimage_Core Graphics_Loadnibnamed - Fatal编程技术网

Ios 拍摄视图快照,而不将其添加到屏幕

Ios 拍摄视图快照,而不将其添加到屏幕,ios,uiview,uiimage,core-graphics,loadnibnamed,Ios,Uiview,Uiimage,Core Graphics,Loadnibnamed,我正在尝试从nib加载视图,对其进行配置,并对其进行快照,而不将其添加到屏幕: + (void)composeFromNibWithImage:(UIImage*)catImage completion:(CompletionBlock)completion { NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"CatNib" owner:nil options:nil]; CatView *catView

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

+ (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的大小都正确,但在我逐步阅读代码时为空。如何从nib加载的视图创建UIImage,而不将视图添加到屏幕

这感觉有点粗糙,但我试过了,它确实完成了任务。如果您从主视图后面的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]”将其删除。

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

我知道我可以通过某种方式将视图添加到屏幕的不可见部分来实现这一点。我实际上是从一个NSObject子类调用这段代码,它没有对主视图的引用,所以我希望有一种方法可以加载nib,自定义nib,并对其进行快照,但我想没有。我认为这对OP和其他访问者更有帮助,当你对你的意图进行解释时。
    UIGraphicsBeginImageContext(view.frame.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();