我從網絡Apple.png和[email protected]下載兩個圖像。我想使用[UIImage imageNamed:@「Apple.png」],因此它可以使用內置功能來檢測它是否應顯示Apple.png或[email protected]。(iPhone)在UIImage中使用外部圖像imageNamed
現在我在哪裏存儲這些圖像?我讀的文檔中的以下內容:
文件的名稱。如果這是第一次加載圖像 ,則該方法將在應用程序的主包中查找 指定名稱的圖像。
阿讓應用程序的主束是要走的路。這是我的代碼看起來像:
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」]仍然無法獲取圖像。有人有想法嗎?
編輯:
我爲UIImage的一個類別:
@implementation UIImage的(ImageNamedExtension)
+ (UIImage *)imageNamed:(NSString *)name fromDirectory:(NSString *)directory {
NSString *name2x = [name stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@", [name pathExtension]] withString:[NSString stringWithFormat:@"@2x.%@", [name pathExtension]]];
NSString *path = [directory stringByAppendingPathComponent:name];
NSString *path2x = [directory stringByAppendingPathComponent:name2x];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0) {
if ([fileManager fileExistsAtPath:path2x]) {
return [UIImage imageWithContentsOfFile:path2x];
}
}
return ([fileManager fileExistsAtPath:path]) ? [UIImage imageWithContentsOfFile:path] : nil;
}
@end
這eventualy的伎倆。感謝所有的幫助。
+1代碼格式。 – WrightsCS 2011-01-21 01:34:20
您無法在iPhone上的主包中創建文件。模擬器可以讓你這樣做,但設備不會/不應該。如果你正在下載,你必須把它放在別的地方。 – 2011-01-21 01:35:07
如果僅實現了@ 2x,則您的類別將停止在iPad(第一代)上(即,也需要1x)。在相同的情況下也可能在iPhone 3GS上打破。 – Jonny 2012-11-05 04:28:25