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:
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.