Image full screen width in SwiftUI

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.


Here is how you add a background image and make it fill the full screen in SwiftUI

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Image("background")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.top)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Tags:

Swift

Swiftui