UIImage imageNamed:@"icon.png"]
用上面的方法加載圖片有問(wèn)題。該方法即可以從bundle中讀取圖片遇汞。這種方法在application bundle的頂層文件夾尋找由供應(yīng)的名字的圖象 未妹。如果找到圖片,裝載到iPhone系統(tǒng)緩存圖象空入。那意味圖片是(理論上)放在內(nèi)存里作為cache的络它。因此如果圖片資源多了或大了,此方式容易引起發(fā)生內(nèi)存警告從而導(dǎo)致自動(dòng)退出的問(wèn)題歪赢。
最好是通過(guò)直接讀取文件路徑[UIImage imageWithContentsOfFile]解決掉這個(gè)問(wèn)題化戳,應(yīng)用示例:
NSString *path = [[NSBundle mainBundle] pathForResource:@”icon”ofType:@”png”];
myImage = [UIImage imageWithContentsOfFile:path];
備注:imageNamed方法是不能通過(guò)路徑進(jìn)行加載圖片的,如果要通過(guò)路徑加載圖片可以通過(guò)下面兩個(gè)方法加載埋凯,一個(gè)是URL一個(gè)是FilePath点楼。
NSImage *image = [[NSImage alloc]initWithContentsOfURL:(NSURL *)];
NSImage *image = [[NSImage alloc]initWithContentsOfFile:(NSString *)];
一、加載圖片問(wèn)題
UIImage image = [UIImage imageNamed:imageFileN?ame];
這種圖片加載方式帶有圖片緩存的功能白对,使用這種方式加載圖片后掠廓,圖片會(huì)自動(dòng)加入系統(tǒng)緩存中,并不會(huì)立即釋放到內(nèi)存甩恼。一些資源使程序中經(jīng)常使用的圖片資源蟀瞧,
使用這種方式會(huì)加快程序的運(yùn)行減少I(mǎi)O操作沉颂,但對(duì)于項(xiàng)目中只用到一次的圖片,如果采用這種方案加載悦污,會(huì)增導(dǎo)致程序的內(nèi)存使用增加铸屉。
以下為官方對(duì)此方法的解釋說(shuō)明:
imageNamed:
Returns the image object associated with the specified filename.
- (UIImage *)imageNamed:( NSString *) name
Parameters
nameThe name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
Return Value
The image object for the specified file, or ?nil if the method could not find the specified image.
Discussion
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already
in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
二、非緩存的加載方式
- (UIImage *)imageWithContentsOfFile:(NSString *)path
- (UIImage *)imageWithData:(NSData *)data
三切端、何時(shí)使用imageNamed方法
1彻坛、采用imageNamed方法的圖片加載情況
圖片資源反復(fù)使用到,如按鈕背景圖片的藍(lán)色背景踏枣,這些圖片要經(jīng)常用到昌屉,而且占用內(nèi)存少
2、不應(yīng)該采用的情況:
(1)圖片一般只使用一次椰于,如一些用戶(hù)的照片資源
(2)圖片資源較大怠益,加載到內(nèi)存后,比較耗費(fèi)內(nèi)存資源