Updated for Xcode 12.0
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:
Image("example-image")
.resizable()
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("example-image")
.resizable()
.aspectRatio(contentMode: .fit)
SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.