如何在不损失视网膜显示质量的情况下将 UIView 捕获到 UIImage [英] How to capture UIView to UIImage without loss of quality on retina display

查看:68
本文介绍了如何在不损失视网膜显示质量的情况下将 UIView 捕获到 UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在普通设备上运行良好,但在视网膜设备上会产生模糊的图像.

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

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

Does anybody know a solution for my issue?

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

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

推荐答案

从使用 UIGraphicsBeginImageContext 切换到 UIGraphicsBeginImageContextWithOptions(如在此页面上).传递 0.0 用于缩放(第三个参数),您将获得一个缩放因子等于屏幕缩放因子的上下文.

Switch from use of UIGraphicsBeginImageContext to UIGraphicsBeginImageContextWithOptions (as documented on this page). Pass 0.0 for scale (the third argument) and you'll get a context with a scale factor equal to that of the screen.

UIGraphicsBeginImageContext 使用固定比例因子 1.0,因此您实际上在 iPhone 4 上获得与在其他 iPhone 上完全相同的图像.我敢打赌,要么 iPhone 4 在您隐式放大时应用了过滤器,要么只是您的大脑发现它不如周围的一切那么敏锐.

UIGraphicsBeginImageContext uses a fixed scale factor of 1.0, so you're actually getting exactly the same image on an iPhone 4 as on the other iPhones. I'll bet either the iPhone 4 is applying a filter when you implicitly scale it up or just your brain is picking up on it being less sharp than everything around it.

所以,我猜:

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

在 Swift 4 中:

And in Swift 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
}

这篇关于如何在不损失视网膜显示质量的情况下将 UIView 捕获到 UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆