How Do I Take a Screen Shot of a UIView?

后端 未结 15 2601
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:28

I am wondering how my iPhone app can take a screen shot of a specific UIView as a UIImage.

I tried this code but all I get is a blank image

15条回答
  •  长发绾君心
    2020-11-22 09:37

    Swift 4 updated :

    extension UIView {
       var screenShot: UIImage?  {
            if #available(iOS 10, *) {
                let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
                return renderer.image { (context) in
                    self.layer.render(in: context.cgContext)
                }
            } else {
                UIGraphicsBeginImageContextWithOptions(bounds.size, false, 5);
                if let _ = UIGraphicsGetCurrentContext() {
                    drawHierarchy(in: bounds, afterScreenUpdates: true)
                    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()
                    return screenshot
                }
                return nil
            }
        }
    }
    

提交回复
热议问题