swift - 在 SwiftUI 中创建透明的模糊 View

标签 swift swiftui blur

我的目标是创建一个模糊 View ,如下图右上角的 View 。 transparent view on top of ocean and sand

我试过 this post 的前 3 个答案,但它们都有相同的问题——当模糊 View 下面有多种颜色时,它只有一种颜色。这是我尝试过的解决方案之一:

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

如您所见,模糊 View 只是一个灰色 View 。您甚至看不到模糊 View 下的黑白条纹。

我希望模糊 View 更加透明,就像您在第一张图片中看到的那样,通过模糊 View 仍然可以看到海洋、沙滩和阴影。如何在 SwiftUI 中创建这样的 View ?

最佳答案

此代码非常接近您的问题,它仅适用于 IOS15 及更高版本:

ZStack{
  Image("background")
  //then comes your look trough button, here just a Rectangle:
  Rectangle()
 .foregroundColor(.secondary)
 .background(.ultraThinMaterial)
 .frame(width: 100, height: 100)
 //then you can add opacity to see a bit more of the background:
 .opacity(0.95)
}

关于swift - 在 SwiftUI 中创建透明的模糊 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65686067/

相关文章:

Swift 简短的执行语法

ios - 获取请求返回 {(//value )} 而不仅仅是值

ios - SwiftUI 组合 : TabView is not updating on selection when property stored in different viewmodel

使用 SegmentedPickerStyle 的 Picker 内的 SwiftUI 自定义字体大小

android - 为什么是android :FLAG_BLUR_BEHIND creating a gradient background in my new activity instead of bluring the window?

javascript - 添加新表单时如何保持表单处于焦点状态?

ios - 在 UIPageViewController (Swift) 中可靠地跟踪页面索引

swift - Firebase 将数据从文本字段存储到存储

animation - 来自 @Published 属性的 SwiftUI 动画从 View 外部更改