使用snapshotViewAfterScreenUpdates创建的UIView的UIImage:

car*_*ton 25 screenshot snapshot uiview uiimage ios7

是否有可能从创建的UIView获取UIImage snapshotViewAfterScreenUpdates?

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;
}
Run Code Online (Sandbox Code Playgroud)

当然可以在不依赖的情况下获取图像snapshotViewAfterScreenUpdates:

UIImage *snapshotImage = [self imageFromView:someView];
Run Code Online (Sandbox Code Playgroud)

不幸的是,在捕捉复杂视图时,drawViewHierarchyInRect速度无法与之匹敌snapshotViewAfterScreenUpdates.我希望UIImage从创建的视图中获取它会更快snapshotViewAfterScreenUpdates,这可能吗?

car*_*ton 20

答案似乎是否定的,Apple的文档隐含地证实了这一点:

如果要将图形效果(如模糊)应用于快照,请改用该drawViewHierarchyInRect:afterScreenUpdates:方法.

值得注意的是,来自WWDC13的iOS会话上的Implementing Engaging UIsnapshotViewAfterScreenUpdates列为最快的方法,但drawViewHierarchyInRect在示例代码中使用.

  • 我认为这不起作用的原因是快照返回的视图实际上不是一个完整的视图.如果您单步执行调试器,您将看到它的类型是'_UIReplicantView'.这让我觉得它只是另一个视图的优化副本,并且没有'完整'UIView的相同"层"特征...... (2认同)