问题描述
这是我截取视图的方式:
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0) view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext()
但是,在视图中,有一个 UIVisualEffectsView 我想从屏幕截图中排除.
我尝试在截取屏幕截图之前隐藏 UIVisualEffectsView 并在之后取消隐藏它,但我不希望用户看到该过程.(如果我只是隐藏视图,他会这样做,因为 iPad 太慢而且看起来屏幕在闪烁......)
有什么想法吗?提前致谢!
推荐答案
我会利用 snapshotViewAfterScreenUpdates() 方法
<块引用>此方法非常有效地捕获视图的当前渲染外观并使用它来构建新的快照视图.您可以将返回的视图用作应用中当前视图的视觉替代.
因此,您可以使用它来向用户显示完整的未更改视图层次结构的覆盖 UIView,同时呈现层次结构的版本以及您在其下所做的更改.
唯一需要注意的是,如果您要捕获视图控制器的层次结构,则必须创建一个"内容视图"子视图,以防止覆盖视图在您对等级制度.然后,您需要将要呈现的视图层次结构添加到此"内容视图".
因此您的视图层次结构将看起来像这样:
UIView // <- Your view overlayView // <- Only present when a screenshot is being taken contentView // <- The view that gets rendered in the screenshot view(s)ToHide // <- The view(s) that get hidden during the screenshot
虽然,如果您能够将 overlayView 添加到视图的超级视图 - 而不是视图本身 - 您根本不需要处理层次结构.例如:
overlayView // <- Only present when a screenshot is being taken UIView // <- Your view – You can render this in the screenshot view(s)ToHide // <- The view(s) that get hidden during the screenshot otherViews // <- The rest of your hierarchy
这样的事情应该可以达到预期的效果:
// get a snapshot view of your content let overlayView = contentView.snapshotViewAfterScreenUpdates(true) // add it over your view view.addSubview(overlayView) // do changes to the view heirarchy viewToHide.hidden = true // begin image context UIGraphicsBeginImageContextWithOptions(contentView.frame.size, false, 0.0) // render heirarchy contentView.drawViewHierarchyInRect(contentView.bounds, afterScreenUpdates: true) // get image and end context let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // reverse changes to the view heirarchy viewToHide.hidden = false // remove the overlay view overlayView.removeFromSuperview()