从屏幕截图中排除视图

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

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0) view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() 

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

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

我会利用snapshotViewAfterScreenUpdates()方法

此方法非常有效地捕获视图的当前渲染外观,并使用它来构build新的快照视图。 您可以使用返回的视图作为应用中当前视图的可视化替身。

因此,您可以使用它来向用户显示完整的未更改视图层次结构的覆盖UIView ,同时使用其下方的更改呈现层次结构的版本。

唯一需要注意的是,如果要捕获视图控制器的层次结构,则必须创build一个“内容视图”子视图,以防止在对层次结构进行更改的屏幕快照中呈现叠加视图。 然后,您需要将要呈现的视图层次结构添加到此“内容视图”中。

所以你的视图层次将会像这样:

 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视图 – 而不是视图本身 – 你不需要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() 

哦,其实,只是下面的代码(SWIFT 4)可以工作。 也就是说,创build一个上下文,并在快照中添加你想要的项目。 无需在实际屏幕上添加视图。

注意: currentView是基于快照的视图,一般来说它将是整个屏幕的视图。 而addViews是你想添加的视图。

 func takeSnapShot(currentView: UIView , addViews: [UIView], hideViews: [UIView]) -> UIImage { for hideView in hideViews { hideView.isHidden = true } UIGraphicsBeginImageContextWithOptions(currentView.frame.size, false, 0.0) currentView.drawHierarchy(in: currentView.bounds, afterScreenUpdates: true) for addView in addViews{ addView.drawHierarchy(in: addView.frame, afterScreenUpdates: true) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() for hideView in hideViews { hideView.isHidden = false } return image! } 

也许最简单的解决scheme不是将不需要的视图包含在屏幕视图的层次结构中。 你可以简单地把它放在上面。