How to show an Image in SwiftUI?

SwiftUI – Image

To show an image in SwiftUI, use Image(_:) struct. Pass the image file name as String to Image(), and it shall display the image in our Application.

Image("filename")

Example

In this example, we shall import an image into our project, and display this image in our Application using Image(_:) struct.

To import an image as an asset into our Project, open Assets.xcassets file, drag and drop the image into the assets window, as shown in the following screenshot.

SwiftUI - Add Image to Assets

Image shall be added to Assets as shown below.

SwiftUI - Image in Assets

Now, modify your ContentView.swift as show below.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
    }
}

sunrise is the Image file name, that we added to assets.

Screenshot

SwiftUI - Display Image

The image is zoomed in, preserving the aspect ratio, to fit the screen entire screen. This may sometimes make the image go beyond the screen.

Auto Resize Image

To auto resize the image, add resizable() modifier to the Image. resizable() modifier allows the image to resize and fit to the available space.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
    }
}

Screenshot

SwiftUI - Display Image

The aspect ratio is not preserved.

Preserve Aspect Ratio

To preserve the aspect ratio, add aspectRatio() modifier to the Image, with .fill or .fit.

With content mode .fit.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
    }
}

Screenshot

With content mode .fill.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fill)
    }
}

Screenshot

Summary

Summarising thisĀ SwiftUI Tutorial, we learned how to display an Image using SwiftUI.