How to resize an image in SwiftUI?

by dandre.keeling , in category: Swift , a year ago

How to resize an image in SwiftUI?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by reagan_barton , a year ago

@dandre.keeling 

To resize an image in SwiftUI, you can use the resizable() modifier on your Image view. Here's an example of how you can use it:

1
2
3
Image("imageName")
    .resizable()
    .frame(width: 200, height: 200)


This will resize the image to have a width of 200 and a height of 200.


Alternatively, you can use the scaledToFit() or scaledToFill() modifiers to automatically resize the image to fit or fill a given frame:

1
2
3
4
Image("imageName")
    .resizable()
    .scaledToFit()
    .frame(width: 200, height: 200)


1
2
3
4
Image("imageName")
    .resizable()
    .scaledToFill()
    .frame(width: 200, height: 200)


The scaledToFit() modifier will scale the image down to fit within the given frame while preserving the aspect ratio of the original image. The scaledToFill() modifier will scale the image up or down to fill the given frame, but may distort the aspect ratio of the original image.


Note that in order to use the resizable() modifier, the image must be stored as a resizable image (for example, as a .pdf file).

by beatrice.lesch , 4 months ago

@dandre.keeling 

If you are using a regular image file (e.g. .png or .jpg), you can use the resizable(capInsets:resizingMode:) modifier to resize the image. Here's an example:

1
2
3
Image("imageName")
    .resizable(capInsets: EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0), resizingMode: .stretch)
    .frame(width: 200, height: 200)


In this example, the .resizable(capInsets:resizingMode:) modifier is used to specify the edge insets (padding) for the image and the resizing mode. The .frame(width:height:) modifier is used to set the desired width and height of the image.


You can adjust the capInsets to control how the image is stretched. The EdgeInsets specifies the padding from each side of the image. In the example above, all edges are set to 0, meaning the entire image will be stretched to fit the specified frame.


The resizingMode parameter determines how the image is resized. You can choose between .stretch, .tile, or .center. In the example above, .stretch is used to stretch the image to fit the frame.


Keep in mind that resizing a regular image file may result in distortion if the original aspect ratio is not preserved. To avoid distortion, it's recommended to use a resizable image format like a .pdf file or SVG image.