[英]How to use image CDN with SwiftUI?
我想在 SwiftUI 中开发一个简单的全屏图像视图,图像应该适合屏幕内部,而且我想从 CDN 获取图像,所以在请求中我需要提供所需图像的大小。
我在网上看到的所有 SwiffUI 的例子都是这样的。
var body: some View {
Image("my-image")
.frame(width: 375.0, height: 812.0)
}
所以我有两个问题。
如何从 URL/链接获取图像?
SwiftUI 的Image组件不提供从 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 设备会有所不同?
为了获得视图的运行时大小,SwiftUI 提供了一个名为GeometryReader的容器视图。 无论您需要哪个组件的大小,都必须将该组件嵌入到 GeometryReader 容器中,该容器使您可以访问其自身的运行时大小。
这是获取图像运行时大小、请求图像 CDN 并将图像加载到全屏视图的完整代码。 在这里,我使用来自 imageOpt图像 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工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.