Skip to main content

How to adjust the way an image is fitted to its space

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to adjust the way an image is fitted to its space 관련

SwiftUI by Example

Back to Home

How to adjust the way an image is fitted to its space | SwiftUI by Example

How to adjust the way an image is fitted to its space

Updated for Xcode 15

SwiftUI's Image view has the ability to be scaled in different ways, just like the content mode of a UIImageView.

By default, image views automatically size themselves to their contents, which might make them go beyond the screen. If you add the resizable() modifier then the image will instead automatically be sized so that it fills all the available space, either in a frame you specify or whatever is available on the screen:

Image("rome")
    .resizable()
    .frame(height: 200)

Download this as an Xcode projectopen in new window

A phone showing an image of the Pantheon in Rome. The image is stretched horizontally.
A phone showing an image of the Pantheon in Rome. The image is stretched horizontally.

However, that may also cause the image to have its original aspect ratio distorted, because it will be stretched in all dimensions by whatever amount is needed to make it fill the space.

If you want to keep its aspect ratio you should add an aspectRatio modifier using either .fill or .fit, like this:

Image("rome")
    .resizable()
    .aspectRatio(contentMode: .fit)
    .frame(width: 250)

Download this as an Xcode projectopen in new window

A phone showing an image of the Pantheon in Rome. The image is no longer stretched.
A phone showing an image of the Pantheon in Rome. The image is no longer stretched.
Similar solutions…
How to dynamically adjust the appearance of a view based on its size and location | SwiftUI by Example

How to dynamically adjust the appearance of a view based on its size and location
How to adjust the position of a view using its offset | SwiftUI by Example

How to adjust the position of a view using its offset
How to adjust the size of a view relative to its container | SwiftUI by Example

How to adjust the size of a view relative to its container
Two-way bindings in SwiftUI | SwiftUI by Example

Two-way bindings in SwiftUI
How to customize the way links are opened | SwiftUI by Example

How to customize the way links are opened

이찬희 (MarkiiimarK)
Never Stop Learning.