zumzum
zumzum

Reputation: 20148

SwiftUI: add border to view without bleeding out?

I have a simple view like this:

struct TestView: View {
    
    var body: some View {
        
        Button(action: {}) {
            Text("Button")
                .padding()
                .foregroundColor(.white)
            
        }
        .background(Color(.gray))
//        .cornerRadius(10)
        .overlay(
            RoundedRectangle(cornerRadius: 10)
                .stroke(.red, lineWidth:4)
        )
        
    }
       
}

It draws this:

enter image description here

I am trying to understand why the border bleeds out of the view (gray area). I want to draw the border so it stays inside the view (in the gray area). It looks like half of its width is out and Half in.

How can I make the border stay inside the overlay bounds?

Upvotes: 6

Views: 2760

Answers (2)

aheze
aheze

Reputation: 30318

How can I make the border stay inside the overlay bounds?

Use strokeBorder(_:lineWidth:antialiased:) instead — this draws an inner stroke.

Button(action: {}) {
    Text("Button")
        .padding()
        .foregroundColor(.white)
}
.background(Color(.gray))
.overlay(
    RoundedRectangle(cornerRadius: 10)
        .strokeBorder(.red, lineWidth: 4) /// here!
)

Red border is inside gray area

Upvotes: 9

Paul Nelson
Paul Nelson

Reputation: 61

If you want it to look like this: enter image description here

        Button(action: {}) {
            Text("Button")
                .padding()
                .foregroundColor(.white)
        }
        .background(Color(.gray))
        .clipShape(RoundedRectangle(cornerRadius:10))
        .overlay(
            RoundedRectangle(cornerRadius: 10)
                .strokeBorder(.red, lineWidth: 4) /// here!
        )

Upvotes: 1

Related Questions