2013-04-05 43 views
3

這是我在這裏的第一個問題:-)如何閱讀局部圖像與imageWithContentsOfFile

我有本地化爲3種語言的圖像icon_new.png。我需要使用像這樣加載它在運行時:

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"icon_new.png"]; 
UIImage *img = [UIImage imageWithContentsOfFile:path]; 

問題與上面的是,它適用於非本地化的圖像,但對於局部的,他們真正的路徑實際上是與en.lproj追加,ZH -Hans.lproj或其他文件夾名稱取決於本地化中包含的語言。

現在我可以檢查什麼是當前的區域,並相應地追加路徑:

// This path would work for image that's localized - for English version of it. 
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"en.lproj/icon_new.png"]; 

但是我不知道是否有自動的方式做到這一點?就像應用程序從適當的區域路徑加載整個UI .xib文件一樣,所以基本上我只是指定圖像名稱而不是完整路徑,並獲得適當的本地化版本。

在此先感謝您的幫助!

回答

2

使用NSBundle-pathForResource:ofType:,它首先搜索主目錄,如果它沒有在那裏找到資源,則檢查相應的本地化目錄。

NSString *path = [[NSBundle mainBundle] pathForResource:@"icon_new" ofType:@"png"]; 
+1

感謝您的快速回答,我試過了,它的工作原理。 – Sinisa 2013-04-05 23:57:26

+0

我不得不在之前將文件添加到Xcode,否則pathForResource方法返回nil。 – Sney 2018-01-30 17:42:02