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

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

    The currently accepted answer is now out of date, at least if you are supporting iOS 7.

    Here is what you should be using if you are only supporting iOS7+:

    + (UIImage *) imageWithView:(UIView *)view
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
        UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return snapshotImage;
    }
    

    Swift 4:

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

    As per this article, you can see that the new iOS7 method drawViewHierarchyInRect:afterScreenUpdates: is many times faster than renderInContext:. benchmark

提交回复
热议问题