Issue With drawViewHierarchyInRect: afterScreenUpdates while taking snapshot

坚强是说给别人听的谎言 提交于 2019-12-04 20:49:44

I've had similar a similar issue in the past. The following might work for you as a workaround:

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

Note that you may lose some accuracy in the screen capture, as it may exclude blurs, and some Core Animation features.

Edit:

There seems to be issues/tradeoffs with both 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!