【问题标题】:Capture image from UIView is not working on iOS 10.3.3从 UIView 捕获图像在 iOS 10.3.3 上不起作用
【发布时间】:2018-04-04 09:10:55
【问题描述】:

我从UIView 内容中捕获image,如下所示,它工作正常,但是当我使用iOS 10.3.3 在我的iPhone5S 中运行它时,捕获的image 仅包含黑色视图。

-(UIImage *)captureImageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

有什么问题? 提前致谢。

【问题讨论】:

  • 你的代码很完美。可能肯定还有其他问题。

标签: ios objective-c image image-capture


【解决方案1】:

您可以按照@LGP 的说明进行操作。

在主线程上使用以下函数,如下所示。

-(UIImage *)captureImageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

主线程代码。

dispatch_async(dispatch_get_main_queue(), ^{
    UIImage *imgResult = [self captureImageFromView:yourView];
});

【讨论】:

  • 非常感谢。解决了我的问题。
【解决方案2】:

尝试改用drawViewHierarchyInRect。如果这也不起作用,那么问题很可能是您捕获了错误的视图或在以某种方式对其进行了更改之后。

-(UIImage *)captureImageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

【讨论】:

  • @Pankil 你打电话给captureImageFromView时屏幕上的视图吗?
  • 视图位于TableViewCell。我捕获选定的单元格UIView
【解决方案3】:

为了斯威夫特

func snapshot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, true, UIScreen.main.scale)
        self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }

对于目标 C

- (UIImage *)captureView {

    UIGraphicsBeginImageContext(yourview.frame.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextFillRect(ctx, yourview.frame);

    [yourview.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    NSLog(@"size %f %f",newImage.size.height,newImage.size.width);

    return newImage;
}

如果需要,在调用隐藏按钮等之前,它也不会显示在图像上。

【讨论】:

  • 仍然会生成黑色图像。
  • 能否请确保您保存为图像的视图也有来自情节提要的参考。
  • UIViewUITableViewCell 内,我捕获选定的UIView
猜你喜欢
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
相关资源
最近更新 更多