【问题标题】:UIImage from a UIView created with snapshotViewAfterScreenUpdates:来自使用 snapshotViewAfterScreenUpdates 创建的 UIView 的 UIImage:
【发布时间】:2013-12-10 19:19:46
【问题描述】:

是否可以从使用snapshotViewAfterScreenUpdates 创建的 UIView 中获取 UIImage?

snapshotViewAfterScreenUpdates 返回的 UIView 在添加为子视图时看起来不错,但以下会产生黑色图像:

UIView *snapshotView = [someView snapshotViewAfterScreenUpdates:YES]; 
UIImage *snapshotImage = [self imageFromView:snapshotView]; 

- (UIImage *)imageFromView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
    // [view.layer renderInContext:UIGraphicsGetCurrentContext()]; // <- same result...
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return img;
}

当然可以不依赖snapshotViewAfterScreenUpdates获取图片:

UIImage *snapshotImage = [self imageFromView:someView];

很遗憾,在捕获复杂视图时,drawViewHierarchyInRect 的速度无法与snapshotViewAfterScreenUpdates 相提并论。我希望从snapshotViewAfterScreenUpdates 创建的视图中获取UIImage 会更快,这可能吗?

【问题讨论】:

    标签: uiview ios7 uiimage screenshot snapshot


    【解决方案1】:

    答案似乎是 NO,而 Apple 的 documentation 含蓄地证实了这一点:

    如果您想对快照应用图形效果(例如模糊),请使用drawViewHierarchyInRect:afterScreenUpdates: 方法 而是。

    值得注意的是,WWDC13 中的 在 iOS 上实现 Engaging UI 会话将 snapshotViewAfterScreenUpdates 列为最快的方法,但在示例代码中使用了 drawViewHierarchyInRect

    【讨论】:

    • 我认为这不起作用的原因是快照返回的视图实际上不是一个完整的视图。如果您单步调试调试器,您会看到它的类型是“_UIReplicantView”。这让我觉得它只是另一个视图的优化副本,没有“完整”UIView 的相同“层”特征......
    • 感谢@MobileVet,很高兴知道这一点。仍然令人沮丧的是,没有办法从一个关于快速屏幕捕获的功能中获取像素......
    • Apple 确认这是不可能的。见:raywenderlich.com/forums/…
    • @CarlosGuzman 感谢您添加该链接,它包含一些有用的解释。
    • 非常令人沮丧。 drawViewHierarchyInRect 太慢并且占用太多 CPU。你会认为有一种简单的方法可以从视图中获取 OpenGL 纹理或至少一个 CVPixelBufferRef,因为无论如何它下面都是 OpenGL...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多