How To Change Image Aspect Ratio In SwiftUI

There are two ways to scale image, scale to fit, and scale to fill. To both of them, you can change the aspect ratio.

You can read more about them in this post.

There is an option to resize the image and change its aspect ratio at the same time.

There is .aspectRatio() view modifier.

It can just have contentMode fill or fit or you can pass new aspect ratio as CGFloat or CGSize, both work in the same way.

The aspect ratio is width to height ratio.

Image without any modifier looks like:

var body: some View {
    
Image(“landscape”)
}

Default image

Basic usage with mode changed to .fit.

var body: some View {
    
Image(“landscape”)
        .
resizable()
        .
aspectRatio(contentMode: .fit)
}

Image scaled to fit

Now let’s change its aspect ratio.

var body: some View {
    
Image(“landscape”)
        .
resizable()
        .
aspectRatio(0.7, contentMode: .fit)
}

Image with 0.7 aspect ratio and scale to fit

The image is still inside bounds.

Let’s squeeze it.

var body: some View {
    
Image(“landscape”)
        .
resizable()
        .
aspectRatio(0.1, contentMode: .fit)
}

Image with 0.1 aspect ratio and scale to fit

It doesn’t look good and I think you don’t need that result in your app but I wanted to show you one of the edges of possibility.

Now, let’s use CGSize instead of CGFloat. The result will be the same as you use CGFloat 0.7.

var body: some View {
    
Image(“landscape”)
        .
resizable()
        .
aspectRatio(CGSize(width: 7, height: 10), contentMode: .fit)
}

Image with 0.7 aspect ratio and scale to fit

For content mode .fill works in the same way.