针对视网膜显示屏的URL图像

15

我有一个从NSURL中获取图像的应用程序。是否可能通知应用程序它们是视网膜('@2x')版本(图像具有视网膜分辨率)?目前我使用以下代码,但在高分辨率显示器上,图像看起来像素化:

NSURL *url = [NSURL URLWithString:self.imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.pictureImageView.image = image;
6个回答

17

在将UIImage添加到图像视图之前,您需要重新调整其大小。

NSURL *url = [NSURL URLWithString:self.imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
CGFloat screenScale = [UIScreen mainScreen].scale;
if (image.scale != screenScale)
    image = [UIImage imageWithCGImage:image.CGImage scale:screenScale orientation:image.imageOrientation];
self.pictureImageView.image = image;

最好避免硬编码比例值,因此避免使用UIScreen调用。有关为什么需要这样做的更多信息,请参阅苹果文档中的UIImagescale属性

除非您的代码正在后台线程上运行,否则最好避免使用NSData-dataWithContentsOfURL:方法,因为它使用同步网络调用,无法监视或取消。您可以在此苹果技术问答中了解有关同步网络和避免它的方法的更多信息。


这在iOS7中不再起作用。请参见下面n13的答案,该答案有效。另外,请参见此处的已接受答案:https://dev59.com/k2035IYBdhLWcg3wSN0G - RajV

12

尝试使用imageWithData:scale:(适用于iOS 6及更高版本)

NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData scale:[[UIScreen mainScreen] scale]];

它也适用于3倍图像吗?(我猜是因为[UIScreen mainScreen] scale] - androniennn

5
您需要设置UIImage的比例。
UIImage* img = [[UIImage alloc] initWithData:data];
CGFloat screenScale = [UIScreen mainScreen].scale;
if (screenScale != img.scale) {
    img = [UIImage imageWithCGImage:img.CGImage scale:screenScale orientation:img.imageOrientation];
}

文档中提到要小心构建所有UIImages时都以相同的比例,否则你可能会遇到奇怪的显示问题,其中一些内容以一半的大小、双倍大小、一半的分辨率等方式显示。为了避免这些问题,请加载全部UIImages在视网膜分辨率下。资源将自动按正确比例加载。对于从URL数据构建的UIImages,您需要设置它。


1

补充一下,我在同样的情况下做了以下操作,非常有效。

double scaleFactor = [UIScreen mainScreen].scale;
        NSLog(@"Scale Factor is %f", scaleFactor);
        if (scaleFactor==1.0) {
            [cell.videoImageView setImageWithURL:[NSURL URLWithString:regularThumbnailURLString];
        }else if (scaleFactor==2.0){
            [cell.videoImageView setImageWithURL:[NSURL URLWithString:retinaThumbnailURLString];
        }

0

@2x约定只是从应用程序包中加载图像的便捷方式。 如果您想在Retina显示屏上显示图像,则必须将其放大2倍:

图像尺寸100x100

视图大小:50x50。

编辑:我认为,如果您正在从服务器加载图像,则最好的解决方案是添加一些附加参数(例如比例),并返回适当大小的图像:

www.myserver.com/get_image.php?image_name=img.png&scale=2

您可以使用[[UIScreen mainScreen] scale]来获取比例。


0

为了在 iPhone 编程中告诉它某个图片是 Retina,你可以像这样做:

UIImage *img = [self getImageFromDocumentDirectory];
img = [UIImage imageWithCGImage:img.CGImage scale:2 orientation:img.imageOrientation];

在我的情况下,TabBarItem 图像是动态的,即从服务器下载。然后 iOS 无法将其识别为 retina。上面的代码片段对我非常有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接