34 - Load an Image in SwiftUI

Images are an essential part of any user interface, and SwiftUI provides a straightforward way to load and display images in your apps. To load an image in SwiftUI, you need to create a new Image view and pass it the name of the image file you’d like to display.

It’s also essential to ensure that the image file you want to display is included in your app. You can add images to your app by dragging and dropping them into the project navigator in Xcode.

Note: If you want to try out the examples, you can download an archive of all the images used in this section here.

Here’s an example of how to load an image in SwiftUI:

struct ContentView: View {
  var body: some View {
    Image("HedgehogInClover")
      .resizable()
      .aspectRatio(contentMode: .fit)
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .padding()
  }
}

The preview should look as follows:

Use SwiftUI's Image view to present images on screen.

In the example above, you create a new Image view and pass it the name of an image file, HedgehogInClover. The view modifiers work together to attractively present the image as follows:

Overall, this series of modifiers ensures that the image is resizable, maintains its aspect ratio, takes up the maximum available space within its parent view and adds some padding around it for visual separation.

How an Image View Behaves by Default

If you don’t specify a frame or size constraints for the Image view, it will try to occupy the space required to display the image at its intrinsic size. This can lead to the image potentially overflowing or being smaller than you might expect, depending on the layout and surrounding views.

To ensure that the Image view fits neatly within its parent view or container, you can apply appropriate frame or size constraints, such as using the frame modifier to specify a fixed width and height or using other layout techniques like GeometryReader.