Blur Effect in SwiftUI

Posted in SwiftUI

April 16th, 2021

⏱ Reading Time: 2 mins

We all have tried to blur images or entire views in iOS apps from time to time, and in UIKit that wasn’t the most straightforward or customizable thing in the world. However, applying blur effect in SwiftUI based apps is extremely easy, as all it takes is simply to call a view modifier.

Blur effect can be applied on any view, not just Images, and contrarily to UIKit, we can explicitly specify the blur amount. Even more, we can also change that amount on the fly and create a nice visual effect while updating it.

To demonstrate the topic, suppose we have the the following Text that displays a happy face:

To blur it, we have call the blur view modifier, passing as argument the blur amount:

However, a fixed blur amount may not always be what we really want. It’s often necessary to have a varying amount value, so in that case there is an additional step that we have to go through.

At first, we need a property marked with the @State property wrapper that will be indicating the current blur amount. Of course, using a @State property is not mandatory; a different source of truth could be used instead, such as an @ObservedObject or an @EnvironmentObject property. But for the demonstration purposes of this post, a @State property is just fine:

We can now replace the fixed value with the blurRadius property:

To make it possible to change the blur amount on the fly, let’s add the following Slider in the view:

We provide two arguments in the Slider initializer; the binding value of the blurRadius property, and a range of values for the blur amount.

Every time the slider will be used, it will be updating the blurRadius property with the new respective value, and that will have instant impact on blur effect applied on the Text:

Blur effect in SwiftUI demo

So, this is all about applying blur effect in SwiftUI, which admittedly, is a really simple task. Now that you know how to do it, go ahead and use it in your own views. Thank you for reading!

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on SerialCoder.dev.

    We respect your privacy. Unsubscribe at any time.