简体   繁体   English

如何在 SwiftUI 中使用模糊效果作为背景?

[英]How can I have a Blur effect as a Background in SwiftUI?

I want to have blur effect as background for my View, as we know, we can blur the view and what is inside, but I do't want blur content of view but I want blur background view to give a glassy blurred through effect as we know.我想将模糊效果作为我的视图的背景,正如我们所知,我们可以模糊视图及其内部的内容,但我不希望模糊视图的内容,但我希望模糊背景视图以提供玻璃般的模糊效果我们知道。 How i can do this in SwiftUi?我如何在 SwiftUi 中做到这一点?

In other words, the under layer of view would be blurred in frame on current view which sets as background for current view.换句话说,视图的下层将在当前视图的框架中模糊,当前视图设置为当前视图的背景。

In iOS 15 you can use Materials, like .ultraThinMaterial在 iOS 15 中,您可以使用材料,例如.ultraThinMaterial

.background(.ultraThinMaterial)

But from iOS 14 down, there is no SwiftUI way to achieve this, though it is possible to create an UIViewRepresentable and place it as a background.但是从 iOS 14 开始,没有 SwiftUI 方法可以实现这一点,尽管可以创建 UIViewRepresentable 并将其放置为背景。

Following code will create a UIViewRepresentable that you are able to use as a background: .systemUltraThinMaterial can be changed to any material以下代码将创建一个 UIViewRepresentable,您可以将其用作背景: .systemUltraThinMaterial可以更改为任何材质

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

View extension (optional):查看扩展(可选):

extension View {
    func backgroundBlurEffect() -> some View {
        self.background(BlurView())
    }
}

Then use on a view like a pop up.然后在弹出窗口之类的视图上使用。

.background(BlurView()) 

or if used like extension或者如果像扩展名一样使用

.backgroundBlurEffect()

See image看图片

You can just use你可以使用

.blur(radius: showCustomAlertView ? 5 : 0)//<< here comes your blur

on your view to blur the view.在您的视图上模糊视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM