2

There have been several discussions regarding how to convert UIView to UIImage, either using view.drawHierarchy(in:) or view.layer.renderInContext(). However, even if set the scale to device scale, the result is still in pretty bad resolution. I wonder if there's a way to transform a UIView to UIImage with high resolution and quality?

hyouuu
  • 2,471
  • 2
  • 27
  • 37
  • 1
    Possible duplicate of [How to capture UIView to UIImage without loss of quality on retina display](https://stackoverflow.com/questions/4334233/how-to-capture-uiview-to-uiimage-without-loss-of-quality-on-retina-display) – Malik Jun 13 '17 at 02:36
  • Thanks, but that is still using the above 2 methods, and the result is still not good :( – hyouuu Jun 13 '17 at 07:02

1 Answers1

6

You need to set the correct content scale on each subview.

extension UIView {   
    func scale(by scale: CGFloat) {
        self.contentScaleFactor = scale        
        for subview in self.subviews {
            subview.scale(by: scale)
        }
    }

    func getImage(scale: CGFloat? = nil) -> UIImage {
        let newScale = scale ?? UIScreen.main.scale
        self.scale(by: newScale)

        let format = UIGraphicsImageRendererFormat()
        format.scale = newScale

        let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: format)

        let image = renderer.image { rendererContext in            
            self.layer.render(in: rendererContext.cgContext)
        }

        return image
    }
}

To create your image:

let image = yourView.getImage()
Gui Del Frate
  • 671
  • 1
  • 7
  • 17