【问题标题】:Getting black (empty) image from UIView drawViewHierarchyInRect:afterScreenUpdates:从 UIView drawViewHierarchyInRect:afterScreenUpdates 获取黑色(空)图像:
【发布时间】:2013-12-09 17:39:28
【问题描述】:

在成功使用 iOS 7 中引入的UIView 的新drawViewHierarchyInRect:afterScreenUpdates: 方法来获取图像表示(通过UIGraphicsGetImageFromCurrentImageContext())后,我的应用程序还需要获取视图的一部分。我设法通过以下方式得到它:

UIImage *image;

CGSize blurredImageSize = [_blurImageView frame].size;

UIGraphicsBeginImageContextWithOptions(blurredImageSize, YES, .0f);

[aView drawViewHierarchyInRect: [aView bounds] afterScreenUpdates: YES];

image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

这让我可以在_blurImageView 的框架之后检索aView 的内容。

然而,现在我需要获得aView 的一部分,但这次这部分将是“内部”。下面是代表我想要实现的图像。

我已经尝试创建一个新的图形上下文并将其大小设置为该部分的大小(红色框)并调用aView 来绘制代表红色框框的矩形(当然它的超级视图的框等于@ 987654330@'s) 但得到的图像全黑(空)。

【问题讨论】:

    标签: ios objective-c uiview cgcontext


    【解决方案1】:

    经过大量调整后,我设法找到了可以完成工作的东西,但是我非常怀疑这是要走的路。

    这是我 [edited-for-Stack Overflow] 的有效代码:

    - (UIImage *) imageOfPortionOfABiggerView
    {
        UIView *bigViewToExtractFrom;
    
        UIImage *image;
    
        UIImage *wholeImage;
    
        CGImageRef _image;
    
        CGRect imageToExtractFrame;
    
        CGFloat screenScale = [[UIScreen mainScreen] scale];
    
        // have to scale the rect due to (I suppose) the screen's scale for Core Graphics.
    
        imageToExtractFrame = CGRectApplyAffineTransform(imageToExtractFrame, CGAffineTransformMakeScale(screenScale, screenScale));
    
    
    
        UIGraphicsBeginImageContextWithOptions([bigViewToExtractFrom bounds].size, YES, screenScale);
    
        [bigViewToExtractFrom drawViewHierarchyInRect: [bigViewToExtractFrom bounds] afterScreenUpdates: NO];
    
        wholeImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        // obtain a CGImage[Ref] from another CGImage, this lets me specify the rect to extract.
        // However since the image is from a UIView which are all at 2x scale (retina) if you specify a rect in points CGImage will not take the screen's scale into consideration and will process the rect in pixels. You'll end up with an image from the wrong rect and half the size.
    
        _image = CGImageCreateWithImageInRect([wholeImage CGImage], imageToExtractFrame);
    
        wholeImage = nil;
    
        // have to specify the image's scale due to CGImage not taking the screen's scale into consideration.
    
        image = [UIImage imageWithCGImage: _image scale: screenScale orientation: UIImageOrientationUp];
    
        CGImageRelease(_image);
    
        return image;
    }
    

    我希望这将帮助任何遇到我的问题的人。随意改进我的 sn-p。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多