'SwiftUI edges visible after using overlay
I'm trying to create rounded edges in one of my views using overlay
.
.background(Color.gray.opacity(0.2))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
The issue is that i still can see the edges on the background and also the stroke. How to crop the edges?
Solution 1:[1]
Your view will not be tappable through overlay, even with transparency, so the solution is to use clip shape and background as shown below
struct DemoRoundRectView: View {
var body: some View {
Text("DEMO")
.frame(width: 100, height: 50)
.background(Color.gray.opacity(0.2))
.clipShape(RoundedRectangle(cornerRadius: 10)) // clip corners
.background(
RoundedRectangle(cornerRadius: 10) // stroke border
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
}
}
Solution 2:[2]
struct ContentView: View {
var body: some View {
Rectangle()
.fill(Color.orange)
.frame(width: 200, height: 200, alignment: .center)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.red, lineWidth: 1)
)
} }
try this.
Solution 3:[3]
It seems that right now your modifiers are something like:
.cornerRadius(10)
.background(Color.gray.opacity(0.2))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
Instead, you need to change the order of the view modifiers, as order matters! You are rounding the corners then applying a background, whereas you should be applying the background so that the corner radius can then clip that.
Try this instead:
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | uikenan |
Solution 3 | George |