Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image full screen width in SwiftUI

Tags:

swift

swiftui

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?

like image 977
LinusGeffarth Avatar asked Jun 04 '19 22:06

LinusGeffarth


People also ask

How do I change the width of a screen in SwiftUI?

To make a SwiftUI view take all available width, we use . frame() modifier with maxWidth and maxHeight set to .

How do I fill a fullscreen view in SwiftUI?

Luckily for us SwiftUI makes this very easy to do. TLDR: To make a view fill the screen or parent view, you can set the maxHeight and maxWidth to . infinity when using the frame view modifier.


1 Answers

The reason .aspectRatio(contentMode:) had no effect on the layout is because you did not make the image resizable with resizeable().

Doing

var body: some View {
    Image("page-under-construction")
    .resizable()
    .aspectRatio(contentMode: .fill)
}

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

var body: some View {
    Image("page-under-construction")
    .resizable()
    .aspectRatio(UIImage(named: "page-under-construction")!.size, contentMode: .fill)
}

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.

like image 127
RPatel99 Avatar answered Sep 20 '22 06:09

RPatel99