LinusG.
LinusG.

Reputation: 28892

Image full screen width in 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?

Upvotes: 40

Views: 35125

Answers (3)

Mr T
Mr T

Reputation: 1499

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()
    }
}

Upvotes: 23

RPatel99
RPatel99

Reputation: 8096

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.

Upvotes: 49

SMP
SMP

Reputation: 1669

Did you try resizable modifier?

struct ImageView: View {
var body: some View {
    Image("turtlerock")
    .resizable()
    .aspectRatio(contentMode: .fit)
}}

Note - There are 2 content modes: .fit and .fill

Upvotes: 8

Related Questions