How to resize Image with SwiftUI? How to resize Image with SwiftUI? ios ios

How to resize Image with SwiftUI?


You should use .resizable() before applying any size modifications on an Image.

Image(room.thumbnailImage)    .resizable()    .frame(width: 32.0, height: 32.0)


How about this:

struct ResizedImage: View {    var body: some View {        Image("myImage")            .resizable()            .scaledToFit()            .frame(width: 200, height: 200)    }}

The image view is 200x200, but the image maintains the original aspect ratio (rescaling within that frame).


Expanding on @rraphael's answer and comments:

As of Xcode 11 beta 2, you can scale an image to arbitrary dimensions, while maintaining the original aspect ratio by wrapping the image in another element.

e.g.

struct FittedImage: View{    let imageName: String    let width: CGFloat    let height: CGFloat    var body: some View {        VStack {            Image(systemName: imageName)                .resizable()                .aspectRatio(1, contentMode: .fit)        }        .frame(width: width, height: height)    }}struct FittedImagesView: View{    private let _name = "checkmark"    var body: some View {        VStack {            FittedImage(imageName: _name, width: 50, height: 50)            .background(Color.yellow)            FittedImage(imageName: _name, width: 100, height: 50)            .background(Color.yellow)            FittedImage(imageName: _name, width: 50, height: 100)            .background(Color.yellow)            FittedImage(imageName: _name, width: 100, height: 100)            .background(Color.yellow)        }    }}

Results

Fitted images preserving aspect ratio

(For some reason, the image is showing as a bit blurry. Rest assured that the real output is sharp.)