swiftimageswiftuisizeresizable

SwiftUI Image with high height layout


I'm trying to get a basic thing, but I can't make it work!

I would like to have a VStack that contains a text an image and a second text. Everything should be visible on the screen. So the Image should resize (crop top and bottom) to give spaces for the two texts... but not.

Without .scaledToFill() it's working well, but the image is stretched

The problem (I think) is because the image has a high height!

(I tried with GeometryReader, fixedSize, layoutPriority, but nothing that I tried works)

The image is from Wikipedia: Image link

struct TestView: View {
    var body: some View {
        VStack(spacing: 8) {
            Text("Text 1")

            Image("image")
                .resizable()
                .scaledToFill()
                .padding()

            Text("Text 2")
        }.background(Color.blue)
    }
}

Simulator screen

What is needed: Image of what is needed

Thank you :)


Solution

  • Ok, I found a way

    Color.clear
        .background(Image("image")
            .resizable()
            .scaledToFill())
        .clipped()
    
    

    Embedding the image as background of a clear Color, the image is limited to the parent size!

    Result: https://i.sstatic.net/PHtd9.jpg