How to take screenshot of portion of UIView?

后端 未结 2 978
时光取名叫无心
时光取名叫无心 2020-12-08 12:02

I want the user to go on my app and take a screenshot of the app after pressing a button programmatically in Swift. I know that UIGraphicsGetImageFromCurrentImageConte

2条回答
  •  一生所求
    2020-12-08 12:42

    This is a previously asked question at How to capture UIView to UIImage without loss of quality on retina display but to expand in swift (2.3):

    extension UIView {
    
        class func image(view: UIView) -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
            guard let ctx = UIGraphicsGetCurrentContext() else {
                return nil
            }
            view.layer.renderInContext(ctx)
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return img
        }
    
        func image() -> UIImage? {
            return UIView.image(self)
        }
    }
    

    So you can either get an image from a view with UIView.image(theView) or by asking the view itself let viewImage = self.view.image()

    Do bear in mind though that this is rough and probably needs further looking at for thread safety etc....

提交回复
热议问题