问题使用drawViewHierarchyInRect:拍摄快照后的AfterScreenUpdates

时间:2017-03-21 03:44:04

标签: objective-c uiview uiimage uigraphicscontext

我在拍摄UIView快照和CAEmitterLayer时遇到问题。下面是我用于拍摄快照的代码:

此处editingView是我的UIView

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

请浏览以下Gif图像链接

链接For afterScreenUpdates:NO(Gif)在这种情况下我缺少快照数据

在这种情况下链接For afterScreenUpdates:YES(Gif)uiview正在闪烁,然后更新并且还面临性能问题。

1 个答案:

答案 0 :(得分:1)

我过去曾遇到过类似的问题。以下内容可能适合您作为解决方法:

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

请注意,您可能会在屏幕截图中失去一些准确性,因为它可能会排除模糊和一些核心动画功能。

修改

renderInContextdrawViewHierarchyInRect似乎存在问题/权衡。以下代码值得一试(取自here以供参考):

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

然后你可以这样做:

CGContextRef context = [self createBitmapContextOfSize:editingView.bounds.size];
[editingView.layer renderInContext:context];

CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage* background = [UIImage imageWithCGImage: cgImage];
CGImageRelease(cgImage);