简体   繁体   English

如何使用 Bundle In SwiftUI with Image

[英]How to Use Bundle In SwiftUI with Image

For example: i have Bundle in project, it is call "Game.Bundle"例如:我在项目中有 Bundle,它叫做“Game.Bundle”

let b :Bundle = Bundle.init(path: Bundle.main.path(forResource:"Game", ofType:"bundle")!)!
Image("Giyuu",bundle:self.b)

but Bundle not work.但捆绑包不起作用。

how can i use custom Bundle我怎样才能使用自定义包

在此处输入图像描述

Your snippet as provided seems to reference b both in self as an instance and as a local variable您提供的代码段似乎在self中将b作为实例和局部变量引用

let b :Bundle = Bundle.init(path: Bundle.main.path(forResource:"Game", ofType:"bundle")!)!
Image("Giyuu",bundle:self.b)

Did you want?你想要吗?

let bundle :Bundle = Bundle.init(path: Bundle.main.path(forResource:"Game", ofType:"bundle")!)!
let image = Image("Giyuu",bundle:bundle)

Or refactored to eliminate force unwraps !或者重构以消除 force unwraps ! with some problem analysis added.添加了一些问题分析。

func getGiyuuImage() -> Image {
    guard let path = Bundle.main.path(forResource:"Game", ofType:"bundle"), let bundle = Bundle(path: path) else {
        fatalError("dev error - no Game bundle")
    }
    let image = Image("Giyuu",bundle: bundle)
    return image
}

The SwiftUI Image(_, bundle: _) looks for image resource in corresponding bundle's Assets catalog. SwiftUI Image(_, bundle: _)在相应的 bundle 的 Assets 目录中查找图像资源。 In your case the image is just embedded as regular file, so you have to find and load it as file.在您的情况下,图像只是作为常规文件嵌入,因此您必须将其作为文件查找并加载。 Image itself cannot do that, so it should be constructed with UIImage that has such possibility. Image本身不能这样做,所以它应该用有这种可能性的UIImage来构造。

So, assuming you Game.bundle is in PlugIns subfolder of main bundle (if not - just correct corresponding path construction below) here is possible approach.因此,假设您的Game.bundle位于主包的PlugIns子文件夹中(如果不是 - 只需在下面更正相应的路径构造),这是可能的方法。

Tested with Xcode 12 / iOS 14用 Xcode 12 / iOS 14 测试

struct ContentView: View {
    var body: some View {
        Image(uiImage: gameImage(name: "test") ?? UIImage())
    }

    func gameImage(name: String, type: String = "png") -> UIImage? {
        guard let plugins = Bundle.main.builtInPlugInsPath,
              let bundle = Bundle(url: URL(fileURLWithPath:
                           plugins).appendingPathComponent("Game.bundle")),
              let path = bundle.path(forResource: name, ofType: type)
              else { return nil }
        return UIImage(contentsOfFile: path)
    }
}

You can use my extension:您可以使用我的扩展程序:

extension Image {
    init(path: String) {
        self.init(uiImage: UIImage(named: path)!)
    }
}

In SwiftUI:在 SwiftUI:

Image(path: "Game.bundle/Giyuu.png")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM