How to set specific Width for Image in SwiftUI?

SwiftUI Image – Width

To set specific width for an Image, add frame() modifier to the Image. You may specify width, height and alignment for Image through frame() modifier.

In this tutorial, we will set a specific width for an Image and our focus is only on the width parameter to frame() modifier.

Example

In this example, we shall display an image from assets in three Image views with different width values. The first Image shall have a width of 100, the second Image shall have a width of 150, and the third image shall have a width of 200.

We have set the resizable() and aspectRatio() modifiers such that the aspect ratio of the image is preserved. So, when a specific width is set, the height is implicitly set using the original aspect ratio of the image.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 100)
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 150)
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 200)
    }
}

Screenshot

Set specific Width for Image in SwiftUI

Summary

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