从屏幕截图中排除视图

Lin*_*rth 3 screenshot view ios swift

这是我截取我的观点的截图:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Run Code Online (Sandbox Code Playgroud)

但是,在视图中,有一个UIVisualEffectsView我想从屏幕截图中排除.
我尝试UIVisualEffectsView在截取屏幕截图之前隐藏它,然后取消隐藏它但我不希望用户看到该过程.(如果我只是隐藏视图,他会这么做,因为iPad太慢而且看起来屏幕闪烁......)

有任何想法吗?提前致谢!

Ham*_*ish 5

我会利用这个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
Run Code Online (Sandbox Code Playgroud)

虽然,如果你能够添加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
Run Code Online (Sandbox Code Playgroud)

这样的事情应该达到预期的效果:

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