首页 > 解决方案 > SwiftUI 中有没有一种模糊背景的方法?

问题描述

我正在寻找模糊视图的背景,但不想闯入 UIKit 来完成它(例如 a UIVisualEffectView)我正在挖掘文档但一无所获,似乎没有办法实时剪辑背景并对其应用效果。我错了还是以错误的方式调查它?

标签: swiftswiftui

解决方案


1. Native SwiftUI 方式:

.blur()只需在您需要模糊的任何内容上添加修饰符,例如:

Image("BG")
   .blur(radius: 20)

模糊演示 注意视图的顶部和底部

请注意,您可以使用Group多个视图并将它们模糊在一起。


2.视觉效果视图:

你可以UIVisualEffectView从 UIKit 中带上级长:

VisualEffectView(effect: UIBlurEffect(style: .dark))

有了这个小结构:

struct VisualEffectView: UIViewRepresentable {
    var effect: UIVisualEffect?
    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView { UIVisualEffectView() }
    func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) { uiView.effect = effect }
}

电动车演示


3. iOS 15:材质

您可以通过一行代码使用 iOS 预定义材料:

.background(.ultraThinMaterial)

演示


推荐阅读