7

我有一些图像需要从网络上获取。仅使用来自 URL 的数据。
它们需要在 Retina 显示屏上正确显示。
当我从网络上获取图像时,它们看起来仍然像素化。我需要将图像的比例设置为视网膜显示(2.0),但我必须遗漏一些东西。这是我到目前为止所做的。

UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:@"http://www.msdomains.com/tmp/test.png"];

CGRect labelFrame = CGRectMake(0,0,64,64);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:labelFrame];
imageView.contentScaleFactor = [UIScreen mainScreen].scale;

[imageView setImage:img];
[self addSubview:imageView];
[imageView release];
4

4 回答 4

7

尝试#@2x.png在 URL 的末尾添加。这不会更改 URL,但图像将被识别为视网膜 @2x 图像。它对我有用,但我将此方法与SDWebImage一起使用。

例如使用http://www.msdomains.com/tmp/test.png#@2x.png.

于 2012-07-15T12:10:39.023 回答
3

您的代码应该按原样工作。我不知道您图像的原始尺寸是多少,但我猜它们是 64x64 像素。为了正确缩小,原始图像需要为 128x128 像素。

作为测试,以下代码在模拟器和我的 iPhone 4 上以 Retina 分辨率正确显示了我的照片:

UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.seenobjects.org/images/mediumlarge/2006-08-19-native-lilac.jpg"]]];

CGRect labelFrame = CGRectMake(0, 0, 375, 249.5);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:labelFrame];

[imageView setImage:img];
[self.view addSubview:imageView];

请注意,它UIImageView是 375x249.5 点,是照片原始(像素)尺寸的一半。此外,设置contentScaleFactor似乎没有必要。

(顺便说一句,在这种情况下,我看不出@2x在 URL 上指定会有所帮助,因为对的调用dataWithContentsOfURL:将返回一个不透明的数据块,没有留下文件名的痕迹。然后传递给的就是那些不透明的数据imageWithData:加载图像。)

于 2012-07-15T14:09:27.960 回答
0

当您直接将图像 URL 分配给 imageView 时,它不会将其视为视网膜。

imageView.imageURL = [NSURL URLWithString:@"http://example.com/image.png"];

不会给你视网膜图像。

因此,尽管您的图像是 200x200,但如果您的 imageView 是 100x100,那么它将从下载的图像中提取 100x100,并在视网膜设备上显示像素化图像。

解决方案是使用 imageView 的 image 属性而不是 imageURL。

imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://example.com/image.png"]]];

这会将 200x200 图像分配给 100x100 的 imageView,因此图像不会被像素化。

于 2014-08-23T22:53:03.027 回答
-1

对于视网膜显示,添加相同的图像,其分辨率正好是原始图像的两倍。不要忘记在此图像名称的末尾添加“@2x”...例如"image_header.png",图像是 320x100,然后"image_header@2x.png"操作系统将自动选择另一个具有名称(尺寸 640x200)的图像用于视网膜显示...希望对您有所帮助

于 2012-07-15T13:02:15.210 回答