我正在从网上Apple.png和Apple@2x.png下载两张图片。我想使用[UIImage imageNamed:@"Apple.png"]
,以便它可以使用内置功能来检测它是否应该显示Apple.png或Apple@2x.png。
现在我在哪里存储这些图片?我在文档中阅读了以下内容:
文件的名称。如果这是 第一次加载图像时 该方法查找带有的图像 应用程序中的指定名称 主要包。
啊所以应用程序的主要包是要走的路。这就是我的代码:
NSString *directory = [[NSBundle mainBundle] bundlePath];
NSString *path = [directory stringByAppendingPathComponent:imageName];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:path contents:dataFetcher.receivedData attributes:nil];
我检查了文件是否在路径的文件夹中创建并且是否正确。我还在我的项目文件中拖了一个Example.png,看看它是否存储在同一个文件夹中,这也是正确的。
但是,[UIImage imageNamed:@"Apple.png"]
仍然无法获取图像。
答案 0 :(得分:2)
您不能对应用下载的图片使用UIImage
'+imageNamed:
方法。该方法确实在应用程序包中查找图像,但是您的应用程序不允许在运行时更改自己的包。
答案 1 :(得分:1)
将图像(当然是异步)下载到应用程序本地存储(即沙箱),并在本地引用它们。然后,您可以使用NSDocumentDirectory
或NSCachesDirectory
始终获取对其位置的引用。
答案 2 :(得分:0)
创建的文件是否具有适当的权限供您访问?保存后确实关闭了文件吗?
答案 3 :(得分:0)
您无法在运行时修改捆绑包。我还认为imageNamed
使用的东西类似于在包含捆绑资源引用的应用程序中初始化的资源图。
试试这个: http://atastypixel.com/blog/uiimage-resolution-independence-and-the-iphone-4s-retina-display/
侨!
答案 4 :(得分:0)
我认为最好的解决方案是在Library文件夹中创建自己的包,例如images.bundle
。在那里你可以为两种分辨率拍摄你的图像。要访问该图像,您可以使用pathForResource:ofType:NSBundle类的方法。它返回适当的图像。比返回路径的初始图像。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSURL *libraryURL = [fileManager URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
if (libraryURL == nil) {
ALog(@"Could not access Library directory\n%@", [error localizedDescription]);
} else {
NSURL *folderURL = [libraryURL URLByAppendingPathComponent:@"images.bundle"];
DLog(@"Future bundle url = %@",folderURL);
if (![fileManager createDirectoryAtURL:folderURL withIntermediateDirectories:YES attributes:nil error:&error]) {
ALog(@"Could not create directory %@\n%@", [folderURL path], [error localizedDescription]);
} else{
NSBundle *bundle = [NSBundle bundleWithURL:folderURL];
// put image and image@2x to the bundle;
[bundle pathForResource:yourImageName ofType:@"png"];
}
}
答案 5 :(得分:0)
OP解决方案。
UIImage的类别:
@implementation UIImage (ImageNamedExtension)
+ (UIImage *)imageNamed:(NSString *)name fromDirectory:(NSString *)directory {
if ([UIScreen mainScreen].scale >= 3.0) {
NSString *path3x = [directory stringByAppendingPathComponent:[[name stringByDeletingPathExtension] stringByAppendingFormat:@"@3x.%@", name.pathExtension]];
UIImage *image = [UIImage imageWithContentsOfFile:path3x];
if (image) {
return image;
}
}
if ([UIScreen mainScreen].scale >= 2.0) {
NSString *path2x = [directory stringByAppendingPathComponent:[[name stringByDeletingPathExtension] stringByAppendingFormat:@"@2x.%@", name.pathExtension]];
UIImage *image = [UIImage imageWithContentsOfFile:path2x];
if (image) {
return image;
}
}
NSString *path = [directory stringByAppendingPathComponent:name];
return [UIImage imageWithContentsOfFile:path];
}
@end