How do I blur an image

Asked on 07/31/2024

1 search

To blur an image, you can use SwiftUI's built-in modifiers. Here is an example from the session "Create custom visual effects with SwiftUI" where a blur effect is applied as part of a custom transition:

import SwiftUI

struct ContentView: View {
    @State private var isVisible = false

    var body: some View {
        VStack {
            if isVisible {
                Image(systemName: "star.fill")
                    .transition(.blur)
            }
            Button("Toggle Image") {
                withAnimation {
                    isVisible.toggle()
                }
            }
        }
    }
}

extension AnyTransition {
    static var blur: AnyTransition {
        AnyTransition.modifier(
            active: BlurModifier(amount: 20),
            identity: BlurModifier(amount: 0)
        )
    }
}

struct BlurModifier: ViewModifier {
    var amount: CGFloat

    func body(content: Content) -> some View {
        content
            .blur(radius: amount)
    }
}

In this example, the BlurModifier is used to apply a blur effect to an image when it appears or disappears. The AnyTransition extension defines a custom transition that uses this modifier.

For more details, you can refer to the session Create custom visual effects with SwiftUI (11:17).

How do I blur an image | Ask WWDC