我的应用程序体积较大,因为它是通用的并且专为 Retina 显示屏设计。我想允许用户从我的服务器下载 Retina 图像,而不是最初将它们包含在应用程序中。
我用下面的代码试过了。唯一的问题是图像存储在 Documents 文件夹中,应用程序不会将它们识别为 Retina 图像
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.test.com/img2@2x.png"]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:@"%@/img2@2x.png",docDir];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
我应该如何保存图像以允许应用程序使用它们?
最佳答案
imageWithData:
方法将始终创建比例为 1.0(非视网膜)的图像。从 bundle 外部的自定义位置创建视网膜感知 UIImage,您需要使用 initWithCGImage:scale:orientation:
方法:
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.test.com/img2@2x.png"]]];
UIImage *retinaImage = [UIImage initWithCGImage:[image CGImage] scale:2.0 orientation:UIImageOrientationUp];
(而且,显然,您不应该同步下载图像...)。
我需要在上一个项目中做同样的事情(从文档目录加载与比例相关的图像),所以我在 UIImage 类别中编写了一个小的便捷方法:
- (id)initWithContentsOfResolutionIndependentFile:(NSString *)path
{
if([[UIScreen mainScreen] scale] == 2.0) {
NSString *path2x = [[path stringByDeletingLastPathComponent]
stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@2x.%@",
[[path lastPathComponent] stringByDeletingPathExtension],
[path pathExtension]]];
if([[NSFileManager defaultManager] fileExistsAtPath:path2x]) {
return [self initWithCGImage:[[UIImage imageWithData:[NSData dataWithContentsOfFile:path2x]] CGImage] scale:2.0 orientation:UIImageOrientationUp];
}
}
return [self initWithContentsOfFile:path];
}
用法:
UIImage *myImage = [[UIImage alloc] initWithContentsOfResolutionIndependentFile:@"/path/to/image.png"];
当在视网膜上时,这将尝试从 /path/to/image@2x.png
加载图像,否则使用 /path/to/image.png
.
关于ios - 保存高分辨率资源,以便应用程序知道它可以在 Retina 设备上使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14692649/