Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

swift - Creating a transparent blur view in SwiftUI

My goal is to create a blur view like the view on the top right corner of the below image. transparent view on top of ocean and sand

I've tried the top 3 answers of this post, but they all have the same problem—the blur view only has 1 color when there are multiple colors underneath it. This is one of the solutions I've tried:

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            VStack{
                ForEach(0..<20, id: .self){ num in
                    Rectangle()
                        .frame(height: 20)
                        .padding(.vertical, 6)
                }
            }
            Blur(style:  .systemThinMaterialLight)
                .mask(
                    VStack(spacing: 0) {
                        Rectangle()
                            .frame(width: 347, height: 139)
                            .padding(.top, 0)
                        Spacer()
                    }
                )
                .allowsHitTesting(false)
        }
    }
}

struct Blur: UIViewRepresentable {
    var style: UIBlurEffect.Style = .systemMaterial
    func makeUIView(context: Context) -> UIVisualEffectView {
        return UIVisualEffectView(effect: UIBlurEffect(style: style))
    }
    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
        uiView.effect = UIBlurEffect(style: style)
    }
}

blur view on top of black and white stripes

As you can see, the blur view is just a single gray view. You can't even see the black and white stripes underneath the blur view.

I want the blur view to be more transparent, like the one you see in the first image where the ocean, the sand, and the shadow are still visible through the blur view. How can I create such a view in SwiftUI?


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

1 Answer

0 votes
by (71.8m points)

This method applies a Gaussian blur to a view.

func blur(radius: CGFloat, opaque: Bool = false) -> some View

Parameters:

  • radius: The radial size of the blur. A blur is more diffuse when its radius is large.
  • opaque: A Boolean value that indicates whether the blur renderer permits transparency in the blur output. Set to true to create an opaque blur, or set to false to permit transparency.
Image("your_Image")
   .resizable()
   .frame(width: 300, height: 300)
   .blur(radius: 20)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...