繁体   English   中英

在 SwiftUI 中创建背景模糊的 RoundedRectangle

[英]Create Background-blurred RoundedRectangle in SwiftUI

我正在使用此代码创建背景模糊视图:

struct Blur: UIViewRepresentable {
    let 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)
    }
}

但是,此代码返回一个背景模糊的常规矩形。 我如何使它变圆?

您可以创建另一个 SwiftUI 视图:

struct BlurCircle: View {
    var body: some View {
        Blur()
            .clipShape(Circle())
    }
}

并像这样使用它:

struct ContentView: View {
    var body: some View {
        BlurCircle()
            .frame(width: 100, height: 100)
    }
}

或者,您可以这样做:

struct ContentView: View {
    var body: some View {
        Blur()
            .frame(width: 100, height: 100)
            .clipShape(Circle())
    }
}

如果您不想在Blur结构之外执行此操作,则可以查看以下答案:

您需要更改视觉效果视图的两个属性cornerRadiusclipsToBounds 你的makeUIView function 看起来像

func makeUIView(context: Context) -> UIVisualEffectView {[]
    let view = UIVisualEffectView(effect: UIBlurEffect(style: style))

    view.cornerRadius = 20  // change this to your radius
    view.clipsToBounds = true

    return view
}

' struct BlurRectangle: View { var body: some View { RoundRectangle(cornerRadius: 25).background(Blur()).frame(width: 100, height: 100) } } '希望对你有帮助

暂无
暂无

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

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