【问题标题】:Load app icon from xcassets从 xcassets 加载应用程序图标
【发布时间】:2013-11-04 09:53:37
【问题描述】:

我想在我的应用中显示应用图标。该图标位于默认资产目录 (Images.xcassets) 中。

如何加载它?我尝试了以下方法,它们都返回nil

image = [UIImage imageNamed:@"AppIcon"];
image = [UIImage imageNamed:@"icon"];
image = [UIImage imageNamed:@"icon-76"];
image = [UIImage imageNamed:@"icon-60"];

资产目录中的其他图像按预期工作。

【问题讨论】:

    标签: ios ios7 xcode5


    【解决方案1】:

    通过检查包,我发现图标图像被重命名为:

    AppIcon76x76~ipad.png
    AppIcon76x76@2x~ipad.png
    AppIcon60x60@2x.png
    

    等等。

    因此,使用[UIImage imageNamed:@"AppIcon76x76"] 或类似的作品。

    这是否记录在某处?

    【讨论】:

    • 这样做很危险。 Apple 可能会更改命名约定,并且您的应用程序将来会中断。我的建议是单独复制 image.xcasset 中的另一个图标。
    • 有没有办法获得更高分辨率的图像?
    【解决方案2】:

    我建议通过检查 Info.plist 来检索图标 URL,因为无法保证图标文件的命名方式:

    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
    imageView.image = [UIImage imageNamed:icon]; 
    

    在这种情况下,我们将获取 CFBundleIconFiles 数组的最后一个图像 URL。它具有最大的分辨率。如果您需要更小的分辨率,请更改此设置。

    【讨论】:

    • 有趣的建议。最好确认 AppIcon 名称是否为公共 API。
    • 在我的例子中,图标的名称不同。所以我不会完全依赖这个名字。
    • 为什么在设置“图标”之后不简单地这样做呢? imageView.image = [UIImage imageNamed:icon];
    • @roberto.buratti 你完全正确,这样更容易。在我的特殊情况下,我实际上需要 URL,但是要创建图像,这样更容易。我已经改变了答案。
    • 谢谢@Yossi,好多了。我已经编辑了答案。
    【解决方案3】:

    按照 Ortwin 的回答,Swift 4 方法:

    func getHighResolutionAppIconName() -> String? {
        guard let infoPlist = Bundle.main.infoDictionary else { return nil }
        guard let bundleIcons = infoPlist["CFBundleIcons"] as? NSDictionary else { return nil }
        guard let bundlePrimaryIcon = bundleIcons["CFBundlePrimaryIcon"] as? NSDictionary else { return nil }
        guard let bundleIconFiles = bundlePrimaryIcon["CFBundleIconFiles"] as? NSArray else { return nil }
        guard let appIcon = bundleIconFiles.lastObject as? String else { return nil }
        return appIcon
    }
    

    那么它可以像这样使用:

    let imageName = getHighResolutionAppIconName()
    myImageView.image = UIImage(named: imageName)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2017-10-08
      • 2021-08-29
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      相关资源
      最近更新 更多