Take a snapshot of the view without adding it to the screen

I am trying to download a view from nib, configure it and take a picture without adding it to the screen:

+ (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); } 

where the snapshot is typical:

 + (UIImage *)snapshot:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0); [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } 

However, both catView and composite size are correct, but empty when I view the code. How can I create a UIImage from a view loaded from a tip without adding a view to the screen?

+6
source share
3 answers

It seems a bit hacky, but I tried and it does its job. If you load a view from your page for the main view, you can take a screenshot of only this layer. Until this is an intensive memory scan, the user will never know that the view has been added to the super view.

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

So, run this code after you upload your pin for your main look. After downloading it, you can remove it with `[catView removeFromSuperiew] '

+1
source

I had a similar problem a while ago, and as far as I can tell, it is impossible to take a picture of the presentation, in fact it is not a screen on . I created a workaround and placed the corresponding view that I wanted to take a snapshot outside of the current boundaries of the ViewControllers view so you wouldn't see it. In this case, you could create a valid snapshot. Hope this helps :)

+3
source
  UIGraphicsBeginImageContext(view.frame.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 
0
source

Source: https://habr.com/ru/post/982468/


All Articles