SwiftUI Shadows and Color Opacity

In this section, you will learn how to add shadows and adjust the color opacity of elements in SwiftUI. Shadows can be used to create depth and dimension in your user interface, while color opacity allows you to adjust the transparency of colors to achieve different visual effects. 

You will also learn how to use the shadow and opacity modifiers in SwiftUI to customize the look of your views. Whether you're designing a sleek and modern user interface or a colorful and playful app, these techniques can help you achieve the look and feel you're aiming for.

When your text, buttons and cards blend too much with the background, you can use drop shadows to make them stand out.

The most flexible way to add shadows to your UI in SwiftUI.

Default Shadow  

  • Using the shadow modifier with a radius value will give you a default iOS drop shadow look. 
  • Customize the radius to make it smaller or bigger.

RoundedRectangle(cornerRadius: 25)
	.shadow(radius: 10)

..

Custom Shadow and Opacity  

  • If you want more options, you can change the color, radius, x and y values. 
  • One trick that I like using is to apply an opacity to a full color. 
  • This will give you the ultimate flexibility for styling and animation.

.shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 10)

..

Multiple Shadows  

  • To add multiple shadows, you can use multiple shadow modifiers. 
  • Make sure that the combined shadows are not too strong, with an opacity of less than 50% combined. 
  • The lighter your background is, the lower this percentage should be. 
  • I personally like to have my radius about double the y position.

.shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 2)
.shadow(color: Color.pink.opacity(0.3), radius: 20, x: 0, y: 10)

..

Text Shadow

Text("Swift ui io .com")
	.font(.title).bold()
	.foregroundColor(.white)
	.shadow(radius: 20)

..

Color Shadow  

Using the Color plus opacity technique, you can easily make your drop shadows using the same color as your card's color.

.shadow(color: Color.pink.opacity(0.3), radius: 20, x: 0, y: 10)

..

Final output:

Now we have a beautiful card that has a well-contrasted text and a glow using the shadow modifier.

 VStack {
            Text("Swift ui io .com")
                .font(.title).bold()
                .foregroundColor(.white)
                .shadow(radius: 20)
        }
        .frame(width: 250, height: 400)
        .background(Color.pink)
        .cornerRadius(20)
        .shadow(color: Color.pink.opacity(0.3), radius: 20, x: 0, y: 10)
        .shadow(color: Color.pink.opacity(0.2), radius: 5, x: 0, y: 2)

..


Comments