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

前端 未结 17 1750
时光取名叫无心
时光取名叫无心 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 00:59

    I have created a Swift extension based on @Dima solution:

    extension UIImage {
        class func imageWithView(view: UIView) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
            view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return img
        }
    }
    

    EDIT: Swift 4 improved version

    extension UIImage {
        class func imageWithView(_ view: UIView) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
            defer { UIGraphicsEndImageContext() }
            view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
            return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        }
    }
    

    Usage:

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))  
    let image = UIImage.imageWithView(view)
    

提交回复
热议问题