首页 > 解决方案 > 如何在 SwiftUI 中使用自定义半径(不使用 UIBlurEffect)模糊下面的视图?

问题描述

我正在尝试在 SwiftUI 中创建磨砂玻璃效果。我有一个背景图像和一个矩形顶部。我想模糊矩形所在的图像。我基本上是在尝试实现玻璃态射外观,但我还没有找到任何在线方法。我不能使用 UIBlurEffect 因为我不相信有任何方法可以设置我需要设置的模糊半径。我也不能在矩形上使用模糊修改器,因为它只会模糊矩形而不是下面的图像。提前致谢。

编辑:

我到目前为止的代码:

import SwiftUI

struct ContentView: View {
    
    @State private var offset = CGSize.zero
    
    var body: some View {
        ZStack {
            
            Image("background")
            
            Image("background")
                .frame(width: 300, height: 180)
                .mask(Rectangle().frame(width: 300, height: 180))
                .blur(radius: 5, opaque: true)
                .brightness(0.2)
                .offset(offset)
                .gesture(
                    DragGesture()
                        .onChanged { gesture in
                            self.offset = gesture.translation
                        }
                )
            
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

标签: swiftswiftuiuiblureffect

解决方案


ZStack 的两个 View 相同,一个模糊,一个不模糊。您还将应用.mask到顶视图以将模糊限制在您想要的区域。

你会想要使用

.blur(radius: someValue, opaque: true)
.brightness(someValue)

并且可能blendMode在 ZStack 中的第三层Color(.systemBackground)具有一些不透明度。

一定要在明暗中测试效果。


推荐阅读