How to set Shadow for Image in SwiftUI?

SwiftUI Image Shadow

To display a shadow for an Image, use shadow() modifier. shadow() modifier accepts optional parameters like color, radius, and x, y coordinate.

Example

In this example, we shall display an Image with a shadow of radius 10.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(height: 100)
            .shadow(radius: 10)
    }
}

Screenshot

Set Shadow for Image in SwiftUI
Shadow for Image

Now, let us increase the shadow radius to 20, and observe the resulting output in UI.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(height: 100)
            .shadow(radius: 20)
    }
}

Screenshot

Set Shadow for Image in SwiftUI - Shadow Radius
Shadow Radius

We can also change the shadow color using color parameter of shadow() modifier. Let us set the shadow color to red.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(height: 100)
            .shadow(color: .red, radius: 10, x: 0.0, y: 0.0)
    }
}

Screenshot

Set Shadow for Image in SwiftUI - Shadow Color
Shadow Color

We can also shift the radius using x, y coordinates.

In the following program, we shall shift the shadow to (5, 10) coordinates.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(height: 100)
            .shadow(color: .red, radius: 10, x: 5.0, y: 10.0)
    }
}

Screenshot

Set Shadow for Image in SwiftUI - Shadow Position Coordinates
Shadow Position Coordinates

We can also have a deeper control of the colors. Assign color parameter with a Color(), where Color() takes parameters like red, green, blue and opacity values.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("sunrise")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(height: 100)
            .shadow(color: Color(.sRGBLinear, red: 0.8, green: 0.4, blue: 0.0, opacity: 0.9), radius: 10, x: 5.0, y: 10.0)
    }
}

Screenshot

Set Shadow for Image in SwiftUI - Shadow Color
Shadow Color

Summary

Summarising thisĀ SwiftUI Tutorial, we learned how to display a shadow for Image in SwiftUI.