Home > front end >  How to hide the overflow of the background colour when adding corner radius in SwiftUI?
How to hide the overflow of the background colour when adding corner radius in SwiftUI?

Time:10-19

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!

CodePudding user response:

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

CodePudding user response:

Simply replace this code:

.background(Color.accentColor.opacity(0.1).cornerRadius(20.0))
  • Related