我想在 SwiftUI 中开发一个简单的全屏 ImageView ,图像应该适合屏幕,而且我想从 CDN 获取图像,所以在请求中我需要提供所需图像的大小。
我在网上看到的所有 SwiffUI 的例子都是这样的。
var body: some View {
Image("my-image")
.frame(width: 375.0, height: 812.0)
}
所以我有两个问题。
最佳答案
如何从 URL/链接获取图像?
SwiftUI 的 图片 组件没有提供从 URL 加载图片的原生方式,建议你使用其中一个开源库而不是实现复杂的图片加载逻辑,我推荐使用 SwiftUI 版本的流行开源库 SDWebImage,它被称为 SDWebImageSwiftUI
这是从图像 URL 加载图像的示例
struct ContentView: View {
var body: some View {
WebImage(url:URL(string: "https://<replace with image URL/link>"))
.resizable()
.placeholder {
Rectangle().foregroundColor(.gray)
}
.indicator(.activity)
.scaledToFit()
.frame(width: 375.0, height:812.0)
}
}
如何获取要请求的图像大小,因为不同的 iOS 设备会有所不同?
为了获取 View 的运行时大小,SwiftUI 提供了一个名为 GeometryReader 的容器 View 。 .无论您需要哪个组件的大小,都必须将该组件嵌入到 GeometryReader 容器中,该容器使您可以访问其自身的运行时大小。
这是获取图像运行时大小、请求图像 CDN 并将图像加载到全屏 View 的完整代码。在这里,我使用来自 imageOpt image CDN 的图像您可以使用任何图像 CDN。
struct ContentView: View {
// Use the URL of imageSet obtained from image CDN
let imageURL = "https://djy8xy980kp8s.cloudfront.net/2e0d6k-p25/q"
var body: some View {
/* Embed the WebImage component inside a GoemetryReader container
* this will give you access to run-time size of the container */
GeometryReader { geo in
WebImage(url:
/* Get the final URL with width & height parameters,
* since you want to fit the image inside full screen
* set crop to false */
imageOptClient.constructURL(imageURL: self.imageURL,
imageSize: CGSize(
// goe.size will give the runtime size of the container
width: geo.size.width,
height: geo.size.height),
crop: false))
.resizable()
.placeholder {
Rectangle().foregroundColor(.gray)
}
.indicator(.activity) // Activity Indicator
.scaledToFit()
.frame(width: geo.size.width, height: geo.size.height,
alignment: .center)
}
}
}
免责声明:我为 imageOpt 工作
关于ios - 如何在 SwiftUI 中使用图像 CDN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636538/