SwiftUI Image

Basic Code Example

Image("Image Asset Name")

To display an image, simply add the image file into your asset library (Assets.xcassets) and then pass the name of the asset as a string to your Image element in Line 1.

Resize Images

Image("Image Asset Name")
  .resizable()

To resize an image, the resizable modifier should be added. This makes the image fit into the screen area.

More modifiers can be added to further resize the image, as demonstrated and explained below.

Aspect Ratio of Images

Image("Image Asset Name")
  .resizable()
  .scaledToFit()
  .aspectRatio(contentMode: .fit)
Image("Image Asset Name")
  .resizable()
  .scaledToFill()
  .aspectRatio(contentMode: .fill)

The modifiers scaledToFit and aspectRatio(contentMode: .fit) on lines 3 and 4 are the same, they both rescale the image to maintain its original aspect ratio and fit on the screen or its frame.

The modifiers scaledToFill and aspectRatio(contentMode: .fill) on lines 7 and 8 both rescale the image so that the image fills the entire screen or its frame.

Frame Images

Image("Image Asset Name")
  .resizable()
  .frame(width: 300, height: 300, alignment: .bottom)

To further change the size of an Image, the frame modifier can be added with parameters width and height to specify the new dimensions. The alignment parameter indicates how the Image will be placed in the frame, which is useful if the frame is larger than the Image.

Note that if the frame modifier is used without the resizable modifier, the image is not resized, but instead the image display is cropped.

Shape of Images

Image("Image Asset Name")
  .resizable()
  .cornerRadius(5)

To do rounded corner images, use the cornerRadius modifier. The integer value passed to the cornerRadius modifier corresponds to the roundness of the corner, with higher numbers corresponding to more rounded corners.

Image("Image Asset Name")
  .resizable()
  .clipShape(Circle())

To change the shape of the image, use the clipShape modifier and pass in the desired shape, such as Circle().

Bonus: Using System Symbols

Image(systemName: "Symbol Name")

Instead of passing the name of an asset to the Image(), system symbols can also be used. SF Symbols are a set of symbols provided by Apple which can also be passed to an Image element, such as in the example above. To browse all available symbols and view their names, Apple provides a downloadable app through this link: https://developer.apple.com/sf-symbols/

Share
Tweet
Pin
Share
Buffer