How to take a screenshot programmatically on iOS

前端 未结 20 2085
一生所求
一生所求 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:23

    Swift 4:

    func makeImage(withView view: UIView) -> UIImage? {
    
        let rect = view.bounds
    
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
    
        guard let context = UIGraphicsGetCurrentContext() else {
          assertionFailure()
          return nil
        }
    
        view.layer.render(in: context)
    
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
          assertionFailure()
          return nil
        }
    
        UIGraphicsEndImageContext()
    
        return image
    }
    

提交回复
热议问题