从UIScreen拍摄快照

时间:2018-04-05 09:09:17

标签: ios swift

我想从包含状态栏的视图中拍摄快照。

以下代码在模拟器中运行,但不在物理设备上运行。

extension UIScreen {

    class func screenshot() -> UIImage {
        let view = main.snapshotView(afterScreenUpdates: false)

        UIGraphicsBeginImageContext(view.bounds.size)
        view.drawHierarchy(in: view, afterScreenUpdates: true)

        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return screenshot!
    }
}

2 个答案:

答案 0 :(得分:0)

要解决您的问题,您可以使用此功能:

func takeScreenshot() -> UIImage? {
    var screenshotImage :UIImage?
    let layer = UIApplication.shared.keyWindow!.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
    guard let context = UIGraphicsGetCurrentContext() else {return nil}
    layer.render(in:context)
    screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return screenshotImage
}

我刚试过这个,它可以在物理设备上运行。

答案 1 :(得分:0)

创建一个扩展程序,如:

extension UIApplication {

    func getViewScreenShot(vc: UIViewController) -> UIImage? {

        let scale = UIScreen.main.scale
        let bounds = vc.view.bounds
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale)
        if UIGraphicsGetCurrentContext() != nil {
            vc.view.drawHierarchy(in: bounds, afterScreenUpdates: true)
            let screenshot = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return screenshot!
        }
        return nil
    }
}

并称之为:

weak var weakSelf = self
let screenShotImage: UIImage = UIApplication.shared.getViewScreenShot(vc: weakSelf!)