How to capture UIView to UIImage without loss of quality on retina display

前端 未结 17 1522
时光取名叫无心
时光取名叫无心 2020-11-22 00:42

My code works fine for normal devices but creates blurry images on retina devices.

Does anybody know a solution for my issue?

+ (UIImage *) imageWith         


        
17条回答
  •  無奈伤痛
    2020-11-22 01:22

    Drop-in Swift 3.0 extension that supports the new iOS 10.0 API & the previous method.

    Note:

    • iOS version check
    • Note the use of defer to simplify the context cleanup.
    • Will also apply the opacity & current scale of the view.
    • Nothing is just unwrapped using ! which could cause a crash.

    extension UIView
    {
        public func renderToImage(afterScreenUpdates: Bool = false) -> UIImage?
        {
            if #available(iOS 10.0, *)
            {
                let rendererFormat = UIGraphicsImageRendererFormat.default()
                rendererFormat.scale = self.layer.contentsScale
                rendererFormat.opaque = self.isOpaque
                let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: rendererFormat)
    
                return
                    renderer.image
                    {
                        _ in
    
                        self.drawHierarchy(in: self.bounds, afterScreenUpdates: afterScreenUpdates)
                    }
            }
            else
            {
                UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, self.layer.contentsScale)
                defer
                {
                    UIGraphicsEndImageContext()
                }
    
                self.drawHierarchy(in: self.bounds, afterScreenUpdates: afterScreenUpdates)
    
                return UIGraphicsGetImageFromCurrentImageContext()
            }
        }
    }
    

提交回复
热议问题