以编程方式快速截图

我试图采取整个视图的截图时,我迅速按下button。 问题是,当我把屏幕截图,一些部分被切断,如顶部…

在这里输入图像说明

其他被切断的部分是我在屏幕底部的容器视图。 它包含一个开关,一个文本框和一个button。 这是我正在使用的截图的代码…

func screenShotMethod() { let layer = UIApplication.shared.keyWindow!.layer let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); layer.render(in: UIGraphicsGetCurrentContext()!) let screenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil) } 

这是我用来创build容器视图的代码…

 lazy var inputContainerView: UIView = { let containerView = UIView() containerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50) containerView.backgroundColor = UIColor.white //Other things... override var inputAccessoryView: UIView? { get { return inputContainerView } } override var canBecomeFirstResponder : Bool { return true } 

这就是压轴形象的样子 在这里输入图像说明

那么我能做些什么来解决呢? 谢谢!

如果你有某种Objective-C知识,那么这里就是你想要的答案。

打开这个链接,并按照遍历所有视图层次结构的最后一个答案和逐行注释来完全理解代码。

图像最终转换成NSDataUIImage 。 如果你仍然困惑,那么我可以把它转换成迅捷,但首先尝试一下你自己。

这是该答案的Swift代码。

 func screenshot() -> UIImage { let imageSize = UIScreen.main.bounds.size as CGSize; UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) let context = UIGraphicsGetCurrentContext() for obj : AnyObject in UIApplication.shared.windows { if let window = obj as? UIWindow { if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main { // so we must first apply the layer's geometry to the graphics context context!.saveGState(); // Center the context around the window's anchor point context!.translateBy(x: window.center.x, y: window.center .y); // Apply the window's transform about the anchor point context!.concatenate(window.transform); // Offset by the portion of the bounds left of and above the anchor point context!.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y); // Render the layer hierarchy to the current context window.layer.render(in: context!) // Restore the context context!.restoreGState(); } } } let image = UIGraphicsGetImageFromCurrentImageContext(); return image! }