0
0
Ios-swiftHow-ToBeginner ยท 3 min read

How to Use Image in SwiftUI: Syntax and Examples

In SwiftUI, use the Image view to display images by specifying the image name or system symbol. You can customize the image with modifiers like resizable() and scaledToFit() to control its size and aspect ratio.
๐Ÿ“

Syntax

The Image view is used to show images in SwiftUI. You create it by passing the image name from your assets or a system symbol name. Common modifiers include resizable() to allow resizing and scaledToFit() to keep the image's aspect ratio.

swift
Image("exampleImage")
  .resizable()
  .scaledToFit()
Output
Displays the image named "exampleImage" resized to fit its container while keeping its aspect ratio.
๐Ÿ’ป

Example

This example shows how to display a local image named "landscape" from your asset catalog. It resizes the image to fit within a frame of 200x200 points while maintaining the aspect ratio.

swift
import SwiftUI

struct ContentView: View {
  var body: some View {
    Image("landscape")
      .resizable()
      .scaledToFit()
      .frame(width: 200, height: 200)
  }
}
Output
A 200x200 points image of "landscape" shown scaled to fit inside the frame without distortion.
โš ๏ธ

Common Pitfalls

Common mistakes include using an image name that does not exist in your assets, which results in a blank space. Also, forgetting resizable() when trying to resize an image will keep it at its original size. Using scaledToFill() instead of scaledToFit() can crop the image unexpectedly.

swift
/* Wrong: Image name typo and missing resizable */
Image("wrongName")

/* Right: Correct name and resizable modifier */
Image("correctName")
  .resizable()
  .scaledToFit()
๐Ÿ“Š

Quick Reference

  • Image("name"): Load image from assets
  • Image(systemName: "symbol"): Load SF Symbol icon
  • resizable(): Make image resizable
  • scaledToFit(): Keep aspect ratio inside frame
  • scaledToFill(): Fill frame, may crop
  • frame(width:height:): Set image size
โœ…

Key Takeaways

Use Image("name") to load images from your asset catalog in SwiftUI.
Apply resizable() before scaling to change image size.
scaledToFit() keeps the image's aspect ratio without cropping.
Check image names carefully to avoid missing images.
Use Image(systemName:) to display built-in SF Symbols easily.