Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

How to clip background blur in SwiftUI

I am trying to have a semi-transparent blurred overlaying view but the blur creates a fuzzy edge and I'd like it to be sharp outlining the overlay shape, ie clip it.

struct TestBlur : View {
    var body : some View {
        HStack {
            VStack {
                Spacer()
                Text("Hello World")
                Spacer()
            }
            .frame(width: 128)
            .background(Color.red.opacity(0.5).blur(radius: 16).clipShape(Rectangle()))
            Spacer()
        }
        .background(Color.yellow)
    }
}

enter image description here

I want the edge of the red overlay to be like so:

enter image description here

In essence I want the red view to blur anything below it and have a sharp edge:

enter image description here

Using @Asperi's BackgroundBlurView also doesn't work, there's no blur done (maybe I am not using this right):

    var body : some View {
        ZStack {
            VStack {
                ForEach(0..<40) { i in
                    Text("ABCDEFGHIKLMNOPQRSTUVWXYZ ABCDEFGHIKLMNOPQRSTUVWXYZ ABCDEFGHIKLMNOPQRSTUVWXYZ ABCDEFGHIKLMNOPQRSTUVWXYZ ABCDEFGHIKLMNOPQRSTUVWXYZ ")
                }
                .rotationEffect(Angle.init(degrees: 0))
            }
            .opacity(0.9)
            .background(Color.yellow)
            
            HStack {
                // Trying to make the below VStack have a semi-transparent background and blur all content below it
                // but the VStack needs to have a sharp edge, not fuzzy.
                VStack {
                    Spacer()
                    Text("Hello World")
                    Spacer()
                }
                .frame(width: 128)
                .background(Color.red.opacity(0.5))
                .background(BackgroundBlurView().opacity(0.8))
                Spacer()
            }
        }
    }

struct BackgroundBlurView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let view = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        DispatchQueue.main.async {
            view.superview?.superview?.backgroundColor = .clear
        }
        return view
    }

    func updateUIView(_ uiView: UIView, context: Context) {}
}

Looks like this (lacks blur): enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...