Resize image in SwiftUI
In this tutorial, we’ll learn how to resize an image in SwiftUI. In SwiftUI the image container automatically takes the size of its content. Whatever image we give to the imageView will be resized to that image. However, SwiftUI gives us different modifiers for modifying and resizing the image.
What we’ll cover in this tutorial
- resizable
- scaledToFit()
- aspectRatio(contentMode: .fit)
- frame
let’s see how we use these modifiers
1) resizable modifier in SwiftUI
This modifier allows us to resize the image. And moreover, it makes the image size equal to its container.
struct ContentView:View{ var body: some View{ VStack(spacing: 20 ){ Image("dark_background") .resizable() }.ignoresSafeArea() } }
This is how the image looks before applying the modifier
This is how it looks after we apply the resizable modifier
Now the image is stretched to fill the entire screen because the modifier stretched the image to take the size of its container which is currently the whole screen.
2) scaledToFit() and Frame in SwiftUI
Sometimes the image is too big and goes beyond its container so that we only see a portion of the image, not the entire image. So to make the image to be entirely visible on the screen we can use the scaledToFit modifier. It will scale the image to fit into its container.
And we can also set the size of the imageview’s container using the frame modifier so that it won’t consider the entire screen its container rather it takes the size for its image from the frame modifier.
So let’s give the imageView a width and height using the frame modifier so it knows what it needs to fit into.
struct ContentView:View{ var body: some View{ VStack(spacing: 20 ){ //scaled to fit modifer will fit the image into its container Image("dark_background") .resizable() .frame(width:200,height: 400) .scaledToFit() }.ignoresSafeArea() } }
3) aspectRatio(contentMode: .fit)
The scaledToFit
()
and aspectRatio
(contentMode: .fit)
modifiers both are the same. They do the same work for us which is fitting the image into its container. We can use any of them they both will give the same result.
Leave a Reply