|

How to Set Image Size in SwiftUI

In this blog post, we take you into the realm of handling image sizes in SwiftUI, an essential aspect of creating visually appealing and user-friendly applications. From maintaining aspect ratios to resizing images while preserving their quality, we’ll cover it all. So, let’s get started!

Basics: Display Image

In SwiftUI, displaying an image is as simple as using the Image view and providing it with the name of your image:

Image("yourImageName")

Resize Image

By default, SwiftUI displays images in their original size, which may not always fit well within your app’s interface. You can change an image’s size using the .resizable() modifier, which makes an image resizable, and then setting the frame:

Image("yourImageName")
    .resizable()
    .frame(width: 100, height: 100)

In this example, the image will be displayed in a frame of 100×100 points.

Preserve Aspect Ratio

Often, you’ll want to resize an image while preserving its aspect ratio to avoid distortion. SwiftUI offers a convenient way to do this using the .aspectRatio() modifier:

Image("yourImageName")
    .resizable()
    .aspectRatio(contentMode: .fit)
    .frame(width: 200)

In this case, the image is resized to fit within a width of 200 points while maintaining its original aspect ratio.

Image size swiftui

Scaled to Fill

Another option is to use the .scaledToFill() modifier. This will make the image fill its frame, potentially exceeding the bounds to maintain its aspect ratio:

Image("yourImageName")
    .resizable()
    .scaledToFill()
    .frame(width: 200, height: 200)
    .clipped()

The .clipped() modifier is used here to prevent the image from exceeding the frame boundaries.

Handling image sizes effectively is a critical skill in SwiftUI development, ensuring your app’s visuals are on point, and improving the overall user experience. By learning how to resize images, preserve their aspect ratios, and fill frames, you can create visually stunning and functional user interfaces in SwiftUI.

Similar Posts

One Comment

Leave a Reply