blub
blub

Reputation: 692

Is there a way to blur the background of a tapped element in SwiftUI?

Let's say I have images in a VStack.

VStack {
    Image1
    Image2
    Image3
    Image4
}

I know how to detect a tap gesture. Is there a way to make it so that, when an image is tapped, the other images become blurred?

I thought about applying a .blur(radius:3) to the VStack and then a .blur(radius:0) to the selected image, but it looks like blurs compound, so that doesn't do anything.

Upvotes: 0

Views: 881

Answers (2)

Asperi
Asperi

Reputation: 257563

Here is a demo of possible approach (as required behaviour not completely clear).

Tested with Xcode 11.4 / iOS 13.4

demo

struct DemoBlurImages: View {
    let images = ["sun.max", "moon", "cloud"]

    @State private var selected: String? = nil

    var body: some View {
        VStack {
            ForEach(images, id: \.self) { name in
                Image(systemName: name).resizable()
                    .onTapGesture {
                        if self.selected == name {
                            self.selected = nil
                        } else {
                            self.selected = name
                        }
                    }
                    .blur(radius: self.selected != nil && self.selected != name ? 10 : 0)
                    .scaleEffect(self.selected == name ? 1.2 : 1)
            }
        }
        .animation(.spring())
        .scaledToFit()
        .frame(width: 100)
    }
}

Upvotes: 4

Spencer Reid
Spencer Reid

Reputation: 459

I try and Idk whether is it that you need. Let's take a look. I will use @State variable to reach your thought.

We can change the status of State variable to control whether the background stacks(VStack, HStack or ZStack) need to be blur or not.

Here is my code:

enter image description here

After we finish all of code, we got this implementation

enter image description here

Upvotes: 0

Related Questions