SwiftUI .scaledToFit()

cslylla's avatar
Published Feb 12, 2023Updated Mar 17, 2023
Contribute to Docs

The .scaledToFit() modifier method scales a view to fit its parent view while maintaining the original aspect ratio.

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours

Syntax

Image("image-file")
    .scaledToFit()

The .scaledToFit() modifier takes no parameters and returns the view scaled with the original aspect ratio.

Example

In the example below, the .scaledToFit() modifier is applied on an image:

import SwiftUI
struct MyStructure: View {
var body: some View {
Image("imagename")
.resizable()
.scaledToFit()
}
}

This will display the following:

SwiftUI ViewModifier scaledToFit

The image is scaled down in the example above with the .scaledToFit() modifier to fit the width of the parent view. The original aspect ratio of the image is maintained.

All contributors

Contribute to Docs

Learn SwiftUI on Codecademy

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours