Problem with drawViewHierarchyInRect: afterScreenUpdates when taking a snapshot

I ran into the problem of taking a UIView snapshot along with CAEmitterLayer . Below is the code I use for the snapshot:

here editingView is my UIView :

 UIGraphicsBeginImageContextWithOptions(editingView.bounds.size, NO, 0.0); [editingView drawViewHierarchyInRect:editingView.bounds afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

Please follow the links below for gif images

Link for For afterScreenUpdates: NO (Gif) in this case I do not have enough snapshot data

Link for For afterScreenUpdates: YES (Gif) in this case, uiview blinks and then updates, and also faces a performance problem.

0
source share
1 answer

I had a similar similar problem in the past. The following steps may work for you as a workaround:

 UIGraphicsBeginImageContextWithOptions(editingView.bounds.size, NO, 0.0); [editingView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

Please note that you may lose some accuracy in screen capture, as this may eliminate blurring and some Core Animation features.

Edit:

There seems to be problems / tradeoffs with renderInContext and drawViewHierarchyInRect . The following code may be worth a try (taken from here for reference):

 - (CGContextRef) createBitmapContextOfSize:(CGSize) size { CGContextRef context = NULL; CGColorSpaceRef colorSpace; int bitmapByteCount; int bitmapBytesPerRow; bitmapBytesPerRow = (size.width * 4); bitmapByteCount = (bitmapBytesPerRow * size.height); colorSpace = CGColorSpaceCreateDeviceRGB(); if (bitmapData != NULL) { free(bitmapData); } bitmapData = malloc( bitmapByteCount ); if (bitmapData == NULL) { fprintf (stderr, "Memory not allocated!"); return NULL; } context = CGBitmapContextCreate (bitmapData, size.width, size.height, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaNoneSkipFirst); CGContextSetAllowsAntialiasing(context,NO); if (context== NULL) { free (bitmapData); fprintf (stderr, "Context not created!"); return NULL; } CGColorSpaceRelease( colorSpace ); CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, size.height); CGContextConcatCTM(context, flipVertical); return context; } 

Then you can do:

 CGContextRef context = [self createBitmapContextOfSize:editingView.bounds.size]; [editingView.layer renderInContext:context]; CGImageRef cgImage = CGBitmapContextCreateImage(context); UIImage* background = [UIImage imageWithCGImage: cgImage]; CGImageRelease(cgImage); 
+1
source

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


All Articles