Blur an image in SwiftUI


This tutorial is going to show you how you can blur an image in SwiftUI with code examples.

I hope you already know How to add an image in SwiftUI. Now let’s see how we can apply the blur effect to our image added using the SwiftUI Image view.

To follow this tutorial, let’s take an image of a tree for example and drag it to the asset library with the asset name tree. Below is our image:

tree

We already know, we can display the image in our app using the Image view:

     Image("tree")
         .frame(width: 300, height: 300)

In the above program, we use the frame() modifier to set the width and height 300.

You can take any other image with any asset name assigned to it.

Now we will see how to blur this image.

Blur image using blur() modifier

In Swift, we can use the blur() modifier to make our SwiftUI image blur as you can see below:

     Image("tree")
         .frame(width: 300, height: 300)
         .blur(radius: 15) // Blur the image

The above program will modify our image and give it a blur effect as you can see below:

Blur tree

We use the radius parameter for the blur() modifier. This parameter defines the radial size of the blur. The blur will be more diffuse if we increase this property value.

You can learn more about the blur() modifier from the official documentation of Apple about blur.

Adding a slider to change the blur amount

Let’s do something more interesting.

Now we are going to make a slider that will control the blur amount. Below is our Swift program for SwiftUI that will do the task:


    @State private var blurAmount = 0.0

      var body: some View {
          
          Slider(value: $blurAmount, in: 0...35, step: 0.1)
          
          Image("tree")
              .frame(width: 300, height: 300)
              .blur(radius: blurAmount)
          
      }
    

If we run it, it will show something like you can see below: