在SwiftUI中创建带有背景模糊效果的圆角矩形

3

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

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)
    }
}

然而,这段代码返回一个具有背景模糊效果的普通矩形。我该如何使其变成圆角矩形?

1
将其四舍五入到外面而不是内部会是更好的方法。 - Asperi
3个回答

5

你可以创建另一个 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结构体之外,你可以查看这个答案:


1

您需要更改视觉效果视图的2个属性,cornerRadiusclipsToBounds。您的makeUIView函数应如下所示:

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

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

    return view
}

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接