39 - Add a Shadow to an Image in SwiftUI

Adding shadows to images can add depth and dimension to your user interface. In SwiftUI, you can add a shadow to an image using the shadow modifier.

Here’s an example of how to add a shadow to an image in SwiftUI:

struct ContentView: View {
  var body: some View {
    Image("CoolCat")
      .resizable()
      .aspectRatio(contentMode: .fit)
      .frame(width: 200, height: 200)
      .shadow(radius: 10)
  }
}
Note: If you want to try out the examples, you can download an archive of all the images used in this section here.

The preview should look as follows:

SwiftUI's shadow modifier adds a shadow to an Image view.

In this example, we are adding a shadow to an image of a cat. The resizable modifier allows the image to be scaled to fit the frame, which we set to width and height of 200. .aspectRatio(contentMode: .fit) preserves the image’s original aspect ratio. The shadow modifier adds a shadow with a radius of 10 points to the image.

Customizing Shadow Color and Radius

You can also customize the shadow by changing the color, opacity, and offset using additional parameters in the shadow modifier. Here’s an example of how to customize the shadow:

struct ContentView: View {
  var body: some View {
    Image("BirdDrinks")
      .resizable()
      .aspectRatio(contentMode: .fit)
      .frame(width: 300, height: 300)
      .shadow(color: .gray, radius: 20, x: 0, y: 2)
  }
}

The preview should look as follows:

Customize the shadow with color and radius parameters.

Here’s what this code does:

Adding shadows to images in SwiftUI is a simple way to enhance the user interface of your app. The shadow modifier can be customized with different parameters to achieve the desired effect.