How to set Aspect Ratio for Image in SwiftUI?

SwiftUI Image – Aspect Ratio

To set specific aspect ratio for an Image, add aspectRatio() modifier to the Image. You may specify aspect ratio, and content mode for Image through aspectRatio() modifier.

In this tutorial, we will set a specific aspect ratio for an Image using aspectRatio() modifier.

Example

In this example, we shall display an image from assets in two Image views with different aspect ratios. The first Image shall display the image with default aspect ratio of the image, ad the second Image shall display the image with an aspect ratio of 20/9.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(height: 100)
            .padding(.bottom, 20)
        Image("sunrise")
            .resizable()
            .aspectRatio(20/9, contentMode: .fit)
            .frame(height: 100)
    }
}

Screenshot

Set Aspect Ratio for Image in SwiftUI

Now, let us display the image in different aspect ratios say 1/1, 4/3, 16/9 and 20/9.

Please note that the image is not clipped while setting its aspect ratio. The image is stretched or shrieked to fit the resulting width and height because of the set aspect ratio.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(1/1, contentMode: .fit)
            .frame(height: 100)
        Image("sunrise")
            .resizable()
            .aspectRatio(4/3, contentMode: .fit)
            .frame(height: 100)
        Image("sunrise")
            .resizable()
            .aspectRatio(16/9, contentMode: .fit)
            .frame(height: 100)
        Image("sunrise")
            .resizable()
            .aspectRatio(20/9, contentMode: .fit)
            .frame(height: 100)
    }
}

Screenshot

set Aspect Ratio for Image in SwiftUI

Summary

Summarising thisĀ SwiftUI Tutorial, we learned how to set aspect ratio for an Image in SwiftUI.