Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide the overflow of the background colour when adding corner radius in SwiftUI?

I want to have a view with rounded corners and a custom background colour, but the latter overflows in the corners, as showed here:

Screenshot of my problem

This is my code:

    var id:Int
    var body: some View {
        VStack(alignment: .leading) {
            Text(name)
                .font(.title2)
                .bold()
                .foregroundColor(.accentColor)
            Text("Index numéro " + String(id))
                .foregroundColor(.accentColor.opacity(0.75))
        }
        .padding()
        .frame(width: UIScreen.width*0.9,
               height: UIScreen.height*0.1,
               alignment: .leading)
        .overlay(RoundedRectangle(cornerRadius: 20)
                    .stroke(Color.accentColor, lineWidth: 3))
        .background(Color.accentColor.opacity(0.1))
    }

Thanks in advance, I hope you guys will help me solve this issue!


1 Answers

You can use a RoundedRectangle with strokeBorder and then a background of an additional RoundedRectangle with a fill modifier. This technique is detailed here: SwiftUI: How to draw filled and stroked shape?

var body: some View {
    VStack(alignment: .leading) {
        Text(name)
            .font(.title2)
            .bold()
            .foregroundColor(.accentColor)
        Text("Index numéro " + String(id))
            .foregroundColor(.accentColor.opacity(0.75))
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .padding()
    .background(
        RoundedRectangle(cornerRadius: 20)
            .strokeBorder(Color.accentColor, lineWidth: 3)
            .background(
                RoundedRectangle(cornerRadius: 20).fill(Color.accentColor.opacity(0.3))
            )
    )
    .padding()
}

Note: I've also changed your .frame modifier and replaced it with padding, which generally would be a more flexible solution that doesn't rely on measuring the screen size, but it's inconsequential to this answer

like image 118
jnpdx Avatar answered Jan 25 '26 19:01

jnpdx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!