How to take a screenshot programmatically on iOS

前端 未结 20 2076
一生所求
一生所求 2020-11-22 01:42

I want a screenshot of the image on the screen saved into the saved photo library.

20条回答
  •  借酒劲吻你
    2020-11-22 02:12

    I couldn't find an answer with Swift 3 implementation. So here it goes.

    static func screenshotOf(window: UIWindow) -> UIImage? {
    
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, true, UIScreen.main.scale)
    
        guard let currentContext = UIGraphicsGetCurrentContext() else {
            return nil
        }
    
        window.layer.render(in: currentContext)
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            return nil
        }
    
        UIGraphicsEndImageContext()
        return image
    }
    

提交回复
热议问题