I added an image to my body in a SwiftUI application and want to have that image cover the full width of the device, but not go over it.
In body
, I return the image object:
var body: some View {
Image("page-under-construction")
}
and the image shows up, however, it's too big:
I tried setting the frame: that affects the highlighted boundaries, but the image does not resize.
In combination, I played around with .aspectRatio(contentMode:)
, which did not seem to have any effect on the layout.
How can I have the image be effectively 100% of the screen width?
Best Answer
The reason
.aspectRatio(contentMode:)
had no effect on the layout is because you did not make the image resizable withresizeable()
.Doing
will cause the image to be the width of the screen, but the image's aspect ratio will not be maintained. To maintain the aspect ratio, do
This utilizes the
.aspectRatio(aspectRatio: CGSize, contentMode: ContentMode)
version of the method your original question discussed with a dummy UIImage to access the Image's original aspect ratio.Note: The explicitly unwrapped optional (
!
) should not be a problem unless you are unsure if the image name is a valid one from your Assets folder. See this post for a comprehensive overview on Swift optionals.