swiftswiftui

SwiftUI - Image not filling container


I have a VStack with fixed width and height. I want the Image to fill the entire width and height of the VStack container, no matter if the image is landscape or portrait oriented.

VStack {
       Image(.document1)
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width: 300, height: 200)
}
.background(.red)

This produces the following result, with red letterboxing from the VStack background color. How can I make sure the Image always scales to fill the entire container?

enter image description here

Edit: This is the document1 image as requested: enter image description here


Solution

  • This is actually fills the container but your original images have invisible padding on both sides, so you can see underneath:

    Demo

    Note that you may want to use .clipped() after setting the frame since the image does not clip by default and you may face something like the following in different ratio setup (I have applied some alpha to make it more understandable):

    Demo 2

    Also, try not to repeat modifiers with same result.