Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add an Image View in SwiftUI
Written by Team Kodeco

SwiftUI makes it incredibly easy to add images to your app’s user interface. In this cookbook entry, you’ll learn how to add an Image View in SwiftUI and customize it to fit your app’s design.

Here’s an example. Drag your profile image into Assets.xcassets, name it Profile, then replace the ContentView struct in ContentView.swift with the following:

struct ContentView: View {
  var body: some View {
    Image("Profile")
      .resizable()
      .aspectRatio(contentMode: .fit)
      .frame(width: 200, height: 200)
      .clipShape(Circle())
      .overlay(Circle().stroke(Color.white, lineWidth: 4))
      .shadow(radius: 7)
  }
}

The preview should look like the following:

A SwiftUI image view with modifiers.
A SwiftUI image view with modifiers.

In this example, we’ve added an Image view that displays an image named “Profile”, and then applied a variety of view modifiers to it:

  • The .resizable() modifier ensures that the image can be resized to fit the frame.
  • The .aspectRatio(contentMode: .fit) modifier maintain the aspect ratio and fits the image to the available space.
  • The .frame(width: 200, height: 200) modifier sets the size of the view to 200x200 pixels.
  • The .clipShape(Circle()) modifier clips the image to a circular shape.
  • The .overlay() modifier adds a four-point white stroke around the circle.
  • The .shadow() modifier adds a shadow to the view.

By chaining together these modifiers in a way that makes sense for your design, you can quickly customize the appearance of your image view.

For more details, see the “Images & Icons in SwiftUI” section in this cookbook.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.