我下载了一个以字节为单位的图像(Data
(。我使用FileManager将其存储在用户设备的缓存中。我想知道我是否可以用Data
或本地URL
创建Image
,我目前正在使用UIImage
,但我想支持macOS。
是否有一种完整的SwiftUI方法可以创建带有URL
的Image
或不带UIKit/UIMImage的Data
?
如果你的问题是关于在macos中显示和镜像,你已经下载了(并且在cachesDirectory
中(,那么试着这样做,从你的镜像中创建一个以字节为单位的镜像:(对macos使用NSImage(
struct ContentView: View {
@State var img = NSImage()
var body: some View {
Image(nsImage: img)
.onAppear {
do {
// local file
let url = try FileManager.default
.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("kat") // <--- your file name here
.appendingPathExtension("png")
print("----> url: (url)")
// even from the net
// let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull%2C_Red_Zone%2C_Christchurch%2C_New_Zealand.jpg")!
if let nsimg = NSImage(contentsOf: url) { img = nsimg }
} catch {
print("(error)")
}
}
}
}