In this tutorial, you will learn how to make a SwiftUI image resizable to fit the screen keeping the actual aspect ratio.
If we place an image in our app view using the SwiftUI
Image() instance, then the result may not be as we expect. For a larger image, the image extends beyond the screen size and we can only view a portion of it.
We can easily overcome the problem by using the Image
resizable() method. But using only this method will not be able to keep the original aspect ratio. To keep the actual aspect ratio and at the same time fit the image to the screen size, we have to use both the
aspectRatio() methods together.
Below is the given SwiftUI code that will perform the task:
Image("image-asset-name") .resizable() .aspectRatio(contentMode: .fit)
In the above Swift code, we have set the
.fit in the
aspectRatio to fit the image to the parent context.
We can also use the
scaledToFit() method to keep the aspect ratio:
Image("image-asset-name") .resizable() .scaledToFit() .aspectRatio(contentMode: .fit)
That’s it. This one line of code shows you how to fit the image to the screen with the actual aspect ratio using SwiftUI.