Mastering Image View in SwiftUI: Resizing, Aspect Ratio, Scale To Fit, and More
In this tutorial, you will learn how to use the Image View in SwiftUI and its various options to control the size and scaling of images. We will explore the resizable modifier, which allows us to adjust the size of an image dynamically. We will also look at the aspectRatio modifier, which lets us maintain the original aspect ratio of an image.
In addition, we will cover the scaleToFit and resizingMode options, which provide additional control over how images are displayed in our SwiftUI views. By the end of this tutorial, you will be able to create stunning image-based UIs in your SwiftUI apps.
Image View gives us access to many features such as rendering mode, resizable and aspect ratio.
Image View
First, you need to import images to the Assets Catalog. Using the Image we pass the name of the image.
Image("fish")
..
Resizing the Image
- By default, the Image will automatically take the original size of the image.
- To make it resize to the container size, we'll use the resizable modifier.
- It will resize the image to fill the screen.
Image("fish")
.resizable()
..
Aspect Ratio
- The aspectRatio modifier allows you to maintain the aspect ratio of the image.
- You can change the contentMode to fill or fit.
Image("fish")
.resizable()
.aspectRatio(contentMode: .fit)
..
Frame Alignment
You can also align your image within the bounds of a frame.
Image("fish")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 200, height: 200, alignment: .center)
..
Tile an Image
To tile the image, add the resizingMode parameter to tile. By default, it's set to stretch.
Image("fish")
.resizable(resizingMode: .tile)
.aspectRatio(contentMode: .fit)
..
Comments
Post a Comment