BLACK FRIDAY: Save 50% on all books and bundles! >>

< Back to Latest Articles

Shadows and glows

SwiftUI gives us a modifier to make simple shadows, but if you want something more advanced such as inner shadows or glows, you need to do extra work. In this article I’ll show you how to get both those effects and more in a customizable, flexible way.

Watch the video here, or read the article below

Layering shadows

SwiftUI gives us a simple shadow() modifier that is good enough for simple purposes. To try it out, create a new Single View App in Xcode, then modify its ContentView to this:

struct ContentView: View {
    var body: some View {
        ZStack {
            Circle()
                .fill(Color.green)
                .frame(width: 300, height: 300)
                .shadow(color: .black, radius: 10)    
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
        .edgesIgnoringSafeArea(.all)
    }
}

That code places a green circle on a white background, and gives the circle a black shadow with a 10-point radius:

However, the effect isn’t very strong even when using a black color, and just increasing the radius doesn’t help much.

Fortunately, SwiftUI has a remarkable trick up its sleeve: we can create multiple shadows for a single view, and the shadows multiply together so the effect becomes significantly darker.

For example, we could repeat our black shadow three times:

Circle()
    .fill(Color.green)
    .frame(width: 300, height: 300)
    .shadow(color: .black, radius: 10)
    .shadow(color: .black, radius: 10)
    .shadow(color: .black, radius: 10)

And now we’ll get a deep black shadow around the circle.

Outer glows

Outer glows are effectively shadows that are brighter than their surroundings, but they don’t work well out of the box because they are very dark.

To see it for yourself, try using this for the body of ContentView:

ZStack {
    Circle()
        .fill(Color.white)
        .frame(width: 300, height: 300)
        .shadow(color: .red, radius: 36)

}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.edgesIgnoringSafeArea(.all)

When you run it, you’ll see the red is obviously there, but it’s not what I’d call glowing.

We can fix this by repeating our shadow trick: if we layer a glow several times we can get increasingly bright effects. The important thing to remember here is that each shadow applies on top of the previous one, so if you don’t want your overall glow size to change you should divide your overall glow size by how many shadow effects you want to repeat.

For example, this applies three shadow effect with a 12-point radius each, making for a 36-point glow in total:

Circle()
    .fill(Color.white)
    .frame(width: 300, height: 300)
    .shadow(color: .red, radius: 12)
    .shadow(color: .red, radius: 12)
    .shadow(color: .red, radius: 12)

That’s much clearer, and it’s something you’ll find yourself doing a lot when creating glows. As a result, I recommend you create a little View extension such as this:

extension View {
    func glow(color: Color = .red, radius: CGFloat = 20) -> some View {
        self
            .shadow(color: color, radius: radius / 3)
            .shadow(color: color, radius: radius / 3)
            .shadow(color: color, radius: radius / 3)
    }
}

And now you can easily replicate your glow effect like this:

Circle()
    .fill(Color.white)
    .frame(width: 300, height: 300)
    .glow(color: .blue, radius: 36)

You can create an interesting variation on this by blurring self in the glow() method as part of the overlay, like this:

self
    .overlay(self.blur(radius: radius / 6))
    .shadow(color: color, radius: radius / 3)
    .shadow(color: color, radius: radius / 3)
    .shadow(color: color, radius: radius / 3)

Try it with and without that overlay, and see which you prefer!

Rainbow glows

If you’d like to try a more advanced effect, we can create a rainbow glow using a background gradient, some blurring, and some masking – it’s quite complex, but the end result looks amazing with something like text.

First, add this extension on View:

extension View {
    func multicolorGlow() -> some View {
        ZStack {
            ForEach(0..<2) { i in
                Rectangle()
                    .fill(AngularGradient(gradient: Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red]), center: .center))
                    .frame(width: 400, height: 300)
                    .mask(self.blur(radius: 20))
                    .overlay(self.blur(radius: 5 - CGFloat(i * 5)))
            }
        }
    }
}

That uses ForEach to create two rectangles, each of which are filled with a rainbow gradient at a precise size. When then mask the gradient using whatever view this method was called on, then overlay the original view with either a 5-point blur or no blur.

To try the effect out, modify your ContentView to this:

Text("Hello World")
    .font(.system(size: 96, weight: .black, design: .rounded))
    .foregroundColor(.white)
    .multilineTextAlignment(.center)
    .frame(width: 400, height: 300)
    .multicolorGlow()

Having two colored rectangles is important, because that’s what gives our glow its strength – we apply the effect more than once. The rectangles are then masked using a blurred version of our original view (the text “Hello World” in our example) so that we get a multi-colored glow.

Finally, drawing the original view as an overlay is what causes the text to appear: it’s drawn once with a small blur so that it brightens up the colors directly around it, then once again with no blue so the text is nice and sharp.

If you wanted a softer look, you could try drawing the blurred original shape on top, like this:

.overlay(self.blur(radius: CGFloat(i * 2)))

Inner shadows

Last but not least, I want to show you how to create an inner shadow effect. We can create this effect by overlaying a new shape on top our existing shape, give it a blurred stroke, then offsetting the blur in our angle direction and masking it with the original shape.

That’s a lot, so let’s break it down and build it up piece by piece in code. First, add this simple innerShadow() method on View that just returns self:

extension View {
    func innerShadow<S: Shape>(using shape: S, angle: Angle = .degrees(0), color: Color = .black, width: CGFloat = 6, blur: CGFloat = 6) -> some View {
        return self
    }
}

We’ll add to that more in just a moment, but first I want you to change ContentView so you can see our results as we go:

struct ContentView: View {
    var body: some View {
        ZStack {
            Circle()
                .fill(Color.green)
                .frame(width: 300, height: 300)
                .innerShadow(using: Circle())
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
        .edgesIgnoringSafeArea(.all)
    }
}

Note: I changed the background color to white to make our inner shadow easier to see.

First we’re going to add a stroke around our shape, using whatever width they specified. This is done as an overlay in SwiftUI, so modify the innerShadow() method to this:

return self.
    .overlay(
        shape
            .stroke(color, lineWidth: width)
    )

If you run it now, you’ll see our green circle has a black line around it. To create our inner shadow effect, we want to move that black line so that it’s thinner at the top than the bottom.

To do that, we’re going to use our input angle with sin() and cos() to calculate which direction to move it in. So, start by adding these two lines of code before return self:

let finalX = CGFloat(cos(angle.radians - .pi / 2))
let finalY = CGFloat(sin(angle.radians - .pi / 2))

That will tell us where the X and Y positions where we should be drawing our overlay, but in the range -1 to 1. To make the effect more pronounced we want to multiply it by some amount of our width.

First, try adding this below the stroke():

.offset(x: finalX * width, y: finalY * width)

That uses the full width of our stroke to multiply the X/Y offset, but if you run that code back you’ll see the bottom part of our green circle peeks out underneath the overlaid black circle – we’ve moved it too far.

When we draw a size X border around a circle, X/2 of the border will be drawn inside the perimeter of the circle and X/2 will be drawn outside. So, the maximum we can safely use for the offset is half our width, which will result in the whole border being drawn on one edge and none on the other edge.

I say “safely” because honestly we can go slightly over to increase our effect, and it won’t be noticeable at all, particularly once we apply the next step! So, try changing your offset to this:

.offset(x: finalX * width * 0.6, y: finalY * width * 0.6)

At this point you’re probably wondering how this is going to look like an inner shadow, because it looks just like a regular stroked circle.

However, try adding a mask for the original shape directly after our offset:

.mask(shape)

And now you’ll see how our effect works: by pushing the stroked circle to one directly then masking it, the parts of our shape that were outside the original circle stop being visible, creating a crescent shape for our shadow.

Of course, we don’t want a solid black line, so I’d like you to add a blur() modifier in between offset() and mask(), like this:

return self
    .overlay(
        shape
            .stroke(color, lineWidth: width)
            .offset(x: finalX * width * 0.6, y: finalY * width * 0.6)
            .blur(radius: blur)
            .mask(shape)
    )

Run it again, and you’ll see now see our black stroke has become hazy, which completes our effect.

Challenge

If you’d like to take these effects further, try these two tasks:

  1. Create an inner glow effect to add to your toolbox. This will need to be based on our current inner glow code, but requires the same layer to get brightness.
  2. Try making our glow effect animate over time, as if the glow were pulsating.

If you liked this, you'd love Hacking with Swift+…

Here's just a sample of the other tutorials, with each one coming as an article to read and as a 4K Ultra HD video.

Find out more and subscribe here


User-friendly network access

14:26

NETWORKING

FREE: User-friendly network access

Anyone can write Swift code to fetch network data, but much harder is knowing how to write code to do it respectfully. In this article we’ll look at building a considerate network stack, taking into account the user’s connection, preferences, and more.

Ultimate Portfolio App: Introduction

14:17

ULTIMATE PORTFOLIO APP

FREE: Ultimate Portfolio App: Introduction

While I’m sure you’re keen to get started programming immediately, please give me a few minutes to outline the goals of this course and explain why it’s different from other courses I’ve written.

Creating a WaveView to draw smooth waveforms

32:08

CUSTOM SWIFTUI COMPONENTS

FREE: Creating a WaveView to draw smooth waveforms

In this article I’m going to walk you through building a WaveView with SwiftUI, allowing us to create beautiful waveform-like effects to bring your user interface to life.

How to use phantom types in Swift

24:11

ADVANCED SWIFT

FREE: How to use phantom types in Swift

Phantom types are a powerful way to give the Swift compiler extra information about our code so that it can stop us from making mistakes. In this article I’m going to explain how they work and why you’d want them, as well as providing lots of hands-on examples you can try.

Trees

31:55

DATA STRUCTURES

FREE: Trees

Trees are an extraordinarily simple, extraordinarily useful data type, and in this article we’ll make a complete tree data type using Swift in just a few minutes. But rather than just stop there, we’re going to do something quite beautiful that I hope will blow your mind while teaching you something useful.

Using memoization to speed up slow functions

36:18

HIGH-PERFORMANCE APPS

FREE: Using memoization to speed up slow functions

In this article you’ll learn how memoization can dramatically boost the performance of slow functions, and how easy Swift makes it thanks to its generics and closures.

Understanding generics – part 1

20:01

INTERMEDIATE SWIFT

FREE: Understanding generics – part 1

Generics are one of the most powerful features of Swift, allowing us to write code once and reuse it in many ways. In this article we’ll explore how they work, why adding constraints actually helps us write more code, and how generics help solve one of the biggest problems in Swift.

Creating a custom property wrapper using DynamicProperty

14:20

INTERMEDIATE SWIFTUI

FREE: Creating a custom property wrapper using DynamicProperty

It’s not hard to make a basic property wrapper, but if you want one that automatically updates the body property like @State you need to do some extra work. In this article I’ll show you exactly how it’s done, as we build a property wrapper capable of reading and writing documents from our app’s container.

Making the most of optionals

23:07

ADVANCED SWIFT

FREE: Making the most of optionals

Swift’s optionals are implemented as simple enums, with just a little compiler magic sprinkled around as syntactic sugar. However, they do much more than people realize, and in this article I’m going to demonstrate some of their power features that can really help you write better code – and blow your mind along the way.

Customizing Label using LabelStyle

17:02

INTERMEDIATE SWIFTUI

Customizing Label using LabelStyle

Labels are one of the simplest views in SwiftUI, but that doesn’t mean there isn’t a lot to explore. In this video I’ll walk you through how to build custom label styles, including adding animation effects triggered by hovering with the iOS trackpad.

Customizing Toggle using ToggleStyle

9:28

INTERMEDIATE SWIFTUI

Customizing Toggle using ToggleStyle

Most of the time the built-in iOS controls are great, but sometimes you want something just a little different. In this article I’m going to walk you through how you can take complete control over the way toggle switches work in SwiftUI, providing custom rendering and interactions.

High-speed computation using Accelerate

36:34

HIGH-PERFORMANCE APPS

High-speed computation using Accelerate

Many coding problems are designed to perform the same operation on lots of data, and in fact they are so common Apple has a whole framework to make it better: Accelerate. In this video I’ll give you an introduction to Accelerate using practical examples so you can see just how easy it is.

Editing projects

19:02

ULTIMATE PORTFOLIO APP

Editing projects

Editing projects is much like editing items, but because a good portfolio project should show off a range of skills we’re going to bring in grids, alerts, tap gestures, and more.

Custom sorting for items

56:13

ULTIMATE PORTFOLIO APP

Custom sorting for items

Our default sort for project items works well enough, but with a little extra work we can let users choose how to sort them. In this article I’m going to walk you through several different ways of approaching this problem, some that I think work well, and others not so much…

Rendering a pie chart

25:37

RENDERING CHARTS IN SWIFTUI

Rendering a pie chart

Pie charts are a classic way of showing divided data visually, and they represent interesting challenges around sizing and angles. In this article we’ll build a complete pie chart view from scratch using SwiftUI, ensuring it works using animation, and also modify it to support donut-style charts too.

Counting Core Data results

20:34

ULTIMATE PORTFOLIO APP

Counting Core Data results

Now that we’ve designed a basic awards UI, we can bring it to life with some Core Data queries to determine which awards have actually been earned.

Cleaning up Core Data

23:38

ULTIMATE PORTFOLIO APP

Cleaning up Core Data

Core Data’s optionals are quite different from Swift’s optionals, which makes them a little uncomfortable to work with. In this article I’m going to show you two ways of fixing this, which will help clear up our code nicely.

Storing your code somewhere safe

21:32

ULTIMATE PORTFOLIO APP

Storing your code somewhere safe

At this point we have something very simple working, so now is a great time to stash your code away somewhere safe using source control. If you already know how to use Git then you’re welcome to skip this part.

Creating a RemoteImage to load images from the web

14:46

CUSTOM SWIFTUI COMPONENTS

Creating a RemoteImage to load images from the web

Just like UIKit before it, SwiftUI doesn’t come with built-in support for loading remote images, which makes it hard to get data from the internet. In this article I’ll show you how you can build a custom view that can fetch image from the internet, while also showing other images for different states.

Creating a particle system in SwiftUI

56:53

SWIFTUI SPECIAL EFFECTS

Creating a particle system in SwiftUI

Particle systems let us create special effects such as confetti, fire, smoke, rain, and snow, all by adjusting a range of inputs. In this article we’re going to build our own particle system entirely driven by SwiftUI, so you can easily add some sparkle to your apps.

Link copied to your pasteboard.