How to capture high resolution image from UIView

二次信任 提交于 2021-02-18 18:49:32

问题


I hope you all are safe.

I know this question asked several times but not getting a perfect answer.

I just wanted to capture an image from UIView with high resolution the main this is that image should not be a blur.

I have tried this code

extension UIView {
    func asImage() -> UIImage {
            let renderer = UIGraphicsImageRenderer(size: self.bounds.size)
            let capturedImage = renderer.image {
                (ctx) in
                self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
            }
            return capturedImage
    }
}

Right now while I capture the image and zoom the text is blurred.

Thanks in advance

Edited I am trying to create high-resolution image from UIView. When I zoom 1 part of image the text is blurred.

Please check below image


回答1:


extension UIView {
    func takeScreenshot() -> UIImage? {
        var screenshotImage :UIImage?
        let layer = self.layer
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale)
        self.drawHierarchy(in: layer.bounds, afterScreenUpdates: true)
        screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return screenshotImage
    }
}

Or maybe you can scale your view (or temporary copy of view) and then take a screenshot.




回答2:


extension UIImage {

    convenience init(view: UIView) {

        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(cgImage: (image?.cgImage)!)

    }
}

using:

let img = UIImage.init(view: self.yourView)



回答3:


extension UIView {
    func takeScreenshot() -> UIImage? {
        var screenshotImage :UIImage?
        let layer = self.layer
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale)
        self.drawHierarchy(in: layer.bounds, afterScreenUpdates: true)
        screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return screenshotImage
    }
}

This answer would be enough, if you want a higher resolution. Just multiple scale to 5 or 10.



来源:https://stackoverflow.com/questions/61942820/how-to-capture-high-resolution-image-from-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!