如何在不损失视网膜显示质量的情况下将UIView捕获到UIImage

我的代码适用于普通设备,但在视网膜设备上创建模糊图像。

有人知道我的问题的解决方案吗?

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

从使用UIGraphicsBeginImageContext切换到UIGraphicsBeginImageContextWithOptions (如本页所述)。 为缩放传递0.0(第三个参数),您将得到一个缩放因子等于屏幕的上下文。

UIGraphicsBeginImageContext使用1.0的固定比例因子,因此您实际上在iPhone 4上获得与其他iPhone上完全相同的图像。 我敢打赌,iPhone 4在应用过滤器时会隐式缩放,或者只是大脑在接近它而不是周围的一切。

所以,我猜想:

#import <QuartzCore/QuartzCore.h>

+ (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

在迅速4:

func image(with view: UIView) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    if let context = UIGraphicsGetCurrentContext() {
        view.layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
    return nil
}

目前接受的答案现在已经过时,至少如果你支持iOS 7的话。

如果您只支持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;
}

根据这篇文章,您可以看到新的iOS7方法drawViewHierarchyInRect:afterScreenUpdates:renderInContext:快了许多倍。 基准http://f.cl.ly/items/323c000h013V2f3R2p3b/Screen%20Shot%202013-09-16%20at%2001.12.37%20.png


我创建了基于@Dima解决方案的Swift扩展:

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
    }
}

编辑:斯威夫特4改进版本

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()
    }
}

用法:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))  
let image = UIImage.imageWithView(view)
链接地址: http://www.djcxy.com/p/25883.html

上一篇: How to capture UIView to UIImage without loss of quality on retina display

下一篇: How to change the name of an iOS app?