【问题标题】:Can not convert UIView to UIImage on NewPad 9.3.5无法在 NewPad 9.3.5 上将 UIView 转换为 UIImage
【发布时间】:2017-03-18 11:10:48
【问题描述】:

使用- (nullable UIView *)resizableSnapshotViewFromRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates withCapInsets:(UIEdgeInsets)从包含AVCaptureVideoPreviewLayer的UIView中进行快照,然后我想将结果(UIView *)转换为UIImage,并显示它,但是UIImage一直是空的。

CGRect frame = CGRectMake(0, 0, 768, 893);
UIView *photo = [self.cameraView resizableSnapshotViewFromRect:frame afterScreenUpdates:YES withCapInsets:UIEdgeInsetsZero];

UIGraphicsBeginImageContextWithOptions(photo.bounds.size, NO, [[UIScreen mainScreen] scale]);
[photo drawViewHierarchyInRect:photo.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView * iv = [[UIImageView alloc] initWithImage:image];
[iv setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
[self addSubview:iv];

CALayer * layer = [iv layer];
layer.borderWidth = 2.0f;
layer.borderColor = [[UIColor orangeColor] CGColor];

有人知道为什么不能得到正确的 UIImage 吗?

Xcode Version 8.2.1 (8C1002) MacOS Sierra 10.12.3(16D32) Deployment Target 9.3 iPad iOS 9.3.5

【问题讨论】:

    标签: ios objective-c uiview uiimage


    【解决方案1】:

    我不知道这个的Objective-C-version,但是尝试自己将它转换为Obj-C,并添加这段代码:

    let context = UIGraphicsGetCurrentContext()
    photo.layer.render(in:context!)
    

    在后面加上

    [photo drawViewHierarchyInRect:photo.bounds afterScreenUpdates:YES];

    但之前

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    【讨论】:

    • [photo.layer renderInContext:UIGraphicsGetCurrentContext()]; 不起作用
    • @leezhm 嗯..我认为它会工作..你确定你的 UIView 已经被绘制了吗?你在那个绘图函数中发送afterScreenUpdates:YES,你知道这段代码是什么意思吗?我不......也许它会等待绘制视图,直到屏幕准备好,但您的其余代码会立即出现。尝试将其更改为NO?
    • 尝试是和否,它不起作用!我的项目是一个iPad App,发现这个话题github.com/jfradj/ScreenshotIssuestackoverflow.com/questions/25432222/…
    【解决方案2】:

    使用以下方法(未经测试):

    - (UIImage *)renderViewToImage:(UIView *)view
    {
        UIImage* image = nil;
    
        UIGraphicsBeginImageContext(view.bounds.size);          
        [view.layer renderInContext: UIGraphicsGetCurrentContext()];        
        image = UIGraphicsGetImageFromCurrentImageContext();            
        UIGraphicsEndImageContext();
    
        return image
    }
    

    然后调用:

    UIImage *img = [self renderViewToImage:photo]
    

    您可能希望将其设为UIView 的类别。

    【讨论】:

    • 我暂时没有机会测试。尝试view.bounds.size 而不是view.frame.size。并让我们知道发生了什么“不起作用”。
    • 没用!我的项目是一个 iPad 应用程序,我发现了这个 github.com/jfradj/ScreenshotIssue
    猜你喜欢
    • 2018-01-09
    • 2011-07-25
    • 2012-12-25
    • 1970-01-01
    • 2015-09-04
    • 2016-12-10
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多