Hekes Pekes
Hekes Pekes

Reputation: 1325

Create Background-blurred RoundedRectangle in SwiftUI

I am using this code to create a background-blurred view:

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

However, this code returns a regular rectangle with background blur. How do I make it rounded?

Upvotes: 3

Views: 2586

Answers (3)

Pastre
Pastre

Reputation: 743

You need to change 2 properies of your visual effect view, cornerRadius and clipsToBounds. Your makeUIView function would look like

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
}

Upvotes: 1

user14321428
user14321428

Reputation:

β€˜ struct BlurRectangle: View { var body: some View { RoundRectangle(cornerRadius: 25) .background(Blur()) .frame(width: 100, height: 100) } } β€˜ Hope it’s helpful 😘

Upvotes: 0

pawello2222
pawello2222

Reputation: 54436

You can create another SwiftUI view:

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

and use it like this:

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

Alternatively, you can just do:

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

If you don't want to do this outside the Blur struct, you can take a look at this answer:

Upvotes: 5

Related Questions