如果您檢查在_image
(無論是NSLog
或在調試器),它可能是nil
。隨着initWithContentsOfFile
你應該指定整個路徑,例如:
NSString *path = [[NSBundle mainBundle] pathForResource:@"TM-1P2" ofType:@"png"];
_image = [[UIImage alloc] initWithContentsOfFile:path];
或者,您可以使用以下,這在束自動查找圖像:
_image = [UIImage imageNamed:@"TM-1P2.png"];
後者的語法,imageNamed
,緩存圖像(即使您關閉視圖控制器也會將其保存在內存中)。如果你不得不在整個應用程序中一次又一次地使用相同的圖像(因爲它不必每次都重新加載),但是如果你只使用一次,那麼這很好,但你可能不想使用imageNamed
。由於imageNamed
文件說:
如果將只顯示一次的圖像文件,並希望確保它不會添加到系統的緩存,你應該使用imageWithContentsOfFile:
而是創建你的形象。這將使您的一次性圖像保留在系統映像緩存之外,這可能會改善應用程序的內存使用特性。
請注意,這兩個都假定您已成功將此圖像添加到您的包中。
如果,另一方面,該圖像是在你的Documents
文件夾,你可以加載它像這樣:
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsPath stringByAppendingPathComponent:@"TM-1P2.png"];
_image = [[UIImage alloc] initWithContentsOfFile:path];
最後,需要注意的是,iOS設備是大小寫敏感的(一般模擬器是不是) ,所以請確保你的大小寫正確。
無關你的問題,在可能不應該在@implementation
定義括號之間的變量,而是你應該把它們放在一個@interface
。例如,你可以把它們放在.h文件中,或者更好的,你可以把它們放在一個專用類延伸在.m文件中,@implementation
前右:
@interface ViewController()
{
NSArray *_pArray;
UIImage *_image;
UIImageView *_imageView;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"TM-1P2" ofType:@"png"];
_image = [[UIImage alloc] initWithContentsOfFile:path];
_imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
[_imageView setImage:_image];
[_imageView setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:_imageView];
}
// ...
@end
來源
2014-02-06 22:29:10
Rob
這是視圖控制器的根視圖控制器你應用程序嗎?你有沒有嘗試改變視圖控制器的背景顏色,以確保它出現? – bneely