Ios 如何在SwiftUI中使用图像CDN?

Ios 如何在SwiftUI中使用图像CDN?,ios,swiftui,Ios,Swiftui,我想在SwiftUI中开发一个简单的全屏图像视图,图像应该适合屏幕的侧面,我还想从CDN获取图像,因此在请求中我需要提供所需图像的大小 我在网上看到的所有SwiffUI示例都是这样的 var body: some View { Image("my-image") .frame(width: 375.0, height: 812.0) } 所以我有两个问题 如何从URL/链接获取图像 如何获取要请求的图像大小,因为不同iOS设备的图像大小不同 如何从URL/链接获取图像? Swi

我想在SwiftUI中开发一个简单的全屏图像视图,图像应该适合屏幕的侧面,我还想从CDN获取图像,因此在请求中我需要提供所需图像的大小

我在网上看到的所有SwiffUI示例都是这样的

var body: some View {
    Image("my-image")
    .frame(width: 375.0, height: 812.0)
}
所以我有两个问题

  • 如何从URL/链接获取图像
  • 如何获取要请求的图像大小,因为不同iOS设备的图像大小不同

  • 如何从URL/链接获取图像?

    SwiftUI的Image组件不提供从URL加载图像的本机方法,建议您使用一个开源库,而不是实现复杂的图像加载逻辑,我建议使用SwiftUI版本流行的开源库SDWebImage,它被称为

    下面是一个从图像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)
      } 
    }
    

    免责声明:我为

    谢谢@oxi工作,这正是我想要的。
    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)
        }
      }
    }