Objective c 用于视网膜显示的URL图像

Objective c 用于视网膜显示的URL图像,objective-c,cocoa-touch,ios,Objective C,Cocoa Touch,Ios,我有一个从NSURL提取图像的应用程序。是否可以告知应用程序它们是视网膜(“@2x”)版本(图像具有视网膜分辨率)?我目前有以下内容,但图像在更高分辨率的显示器上显示为像素化: NSURL *url = [NSURL URLWithString:self.imageURL]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; self.pictureI

我有一个从
NSURL
提取图像的应用程序。是否可以告知应用程序它们是视网膜(“@2x”)版本(图像具有视网膜分辨率)?我目前有以下内容,但图像在更高分辨率的显示器上显示为像素化:

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

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

图像大小100x100

视图大小:50x50

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

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

您可以使用[[UIScreen mainScreen]缩放]

获得缩放。在将UIImage添加到图像视图之前,您需要重新缩放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;
最好避免硬编码刻度值,从而避免UI屏幕调用。请参阅上的苹果文档,以了解有关为什么需要这样做的更多信息


最好避免使用
NSData
-dataWithContentsOfURL:
方法(除非您的代码在后台线程上运行),因为它使用的是无法监视或取消的同步网络调用。您可以阅读更多关于同步联网的痛苦以及避免这种痛苦的方法。

除此之外,我特别做了以下几点,在同样的情况下,工作起来很有魅力

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

您需要在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,否则可能会出现奇怪的显示问题,其中显示的是一半大小、两倍大小、半分辨率等等。要避免所有这些,请以视网膜分辨率加载所有UIImage。资源将以正确的比例自动加载。对于从URL数据构建的UIImage,您需要设置它。

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


要以编程方式告诉iPhone特定图像是视网膜,可以执行以下操作:

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

在我的例子中,
TabBarItem
image是动态的,即从服务器下载。那么iOS就无法将其识别为视网膜。上面的代码片段对我来说非常有用

谢谢!看起来正是我要找的!这在iOS7中不再起作用。请参见下面n13的答案,该答案有效。此外,请参见此处接受的答案:它也适用于3倍图像?(我想是因为
[UIScreen mainScreen]比例]
UIImage *img = [self getImageFromDocumentDirectory];
img = [UIImage imageWithCGImage:img.CGImage scale:2 orientation:img.imageOrientation];