【问题标题】:How to read localized image with imageWithContentsOfFile如何使用 imageWithContentsOfFile 读取本地化图像
【发布时间】:2013-04-05 23:15:58
【问题描述】:

这是我的第一个问题:-)

我有一个图像 icon_new.png 已本地化为 3 种语言。我需要在运行时使用类似这样的方式加载它:

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 文件一样,基本上我只会指定图像名称而不是完整路径,并获得正确的本地化版本。

提前感谢您的帮助!

【问题讨论】:

    标签: ios objective-c image cocoa-touch localization


    【解决方案1】:

    使用NSBundle-pathForResource:ofType:,它首先搜索主目录,如果在主目录中找不到资源,则检查相应的本地化目录。

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

    【讨论】:

    • 我之前必须将文件添加到 Xcode,否则 pathForResource 方法返回 nil。
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多