我如何从一个有效的路径或URL从Bundle在SwiftUI加载图像到图像()?



我的Bundle中有一个PNG文件。我想在SwiftUI中使用那个URL或路径来提供我的图像,现在我在使用这个down代码,但我喜欢只使用SwiftUI而不是UIKit mixed

Image(uiImage: UIImage(contentsOfFile: path)!)

我们有一些初始化图像的方式接受路径或url吗?

如果你想从一个文件路径初始化,你可以在Image上创建一个扩展来为你处理样板代码。但是你需要处理如果UIImage不存在的情况,因为Image(uiImage:)期望一个非可选的UIImage作为参数。

应该这样做:

extension Image {
init(contentsOfFile: String) {
// You could force unwrap here if you are 100% sure the image exists
// but it is better to handle it gracefully
if let image = UIImage(contentsOfFile: contentsOfFile) {
self.init(uiImage: image)
} else {
// You need to handle the option if the image doesn't exist at the file path
// let's just initialize with a SF Symbol as that will exist
// you could pass a default name or otherwise if you like
self.init(systemName: "xmark.octagon")
}
}
}

你可以这样使用它:

Image(contentsOfFile: "path/to/image/here")

或者您可以使用UIImage的属性从包

中加载
extension Image {
init(uiImageNamed: String) {
if let image = UIImage(named: uiImageNamed, in: .main, compatibleWith: nil) {
self.init(uiImage: image)
} else {
// You need to handle the option if the image doesn't exist at the file path
self.init(systemName: "xmark.octagon")
}
}
}

你可以这样使用它:

Image(uiImageNamed: "ImageName")

最新更新