swiftuiswiftui-image

SwiftUI scale image only if it is bigger


I am trying to ensure that my image is at most 80 by 120:

Image(MY_IMAGE, bundle: nil)
    .resizable()
    .aspectRatio(contentMode: .fit)
    .frame(maxWidth:120, maxHeight: 80)

This works, but for some reason images which are smaller than allowed size, say 40 by 60, get scaled upwards.

How can I tell SwiftUI to constrain image to 80 by 120 if it is bigger, but keep original size if it is smaller?


Solution

  • You can use ViewThatFits, supplying the unscaled image, followed by the scaled image.

    The documentation to ViewThatfits states:

    ViewThatFits evaluates its child views in the order you provide them to the initializer. It selects the first child whose ideal size on the constrained axes fits within the proposed size.

    ViewThatFits {
        Image(MY_IMAGE, bundle: nil)
    
        Image(MY_IMAGE, bundle: nil)
            .resizable()
            .scaledToFit()
    }
    .frame(maxWidth:120, maxHeight: 80)
    .fixedSize()
    

    By applying .fixedSize(), it only occupies the space it actually needs. So it does not expand to the maximum width and height, unless it needs to for an image that is scaled down to fit.