I want to develop a simple full screen image view in SwiftUI, the image should fit in side the screen, also I want to fetch the image from a CDN so in the request I need to provide the size of the required image.
All the example of SwiffUI I see on the net are some like this.
var body: some View {
Image("my-image")
.frame(width: 375.0, height: 812.0)
}
So I have two question.
How do I fetch image from URL/link?
SwiftUI's Image component doesn't provide a native way to load image from an URL, suggest you use one of the open source libraries instead of implementing complex image loading logic, I recommend using SwiftUI version popular open source library SDWebImage, it is called SDWebImageSwiftUI
Here is an example to load an image from image 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)
}
}
How do I get the size of the image to request, as it will be different for different iOS devices?
To get the run-time size of a view, SwiftUI provides a container view called GeometryReader . Whichever component's size you need you have to embed that component(s) inside a GeometryReader container, this container give you access to the run-time size of itself.
Here is complete code to get the run-time size of an image, make a request to image CDN and load the image into full screen view. Here I am using image from imageOpt image CDN you can use any image 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)
}
}
}
disclaimer: I work for imageOpt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.