Updated for Xcode 12.5
SwiftUI provides the fill()
, stroke()
, and strokeBorder()
modifiers for adjusting the way we draw shapes, but it does not provide a built-in way to fill and stroke at the same time. However, we can get the same effect in two different ways, and I’m going to show you both here.
The first option is to use strokeBorder()
to add a border around your shape, then place a filled shape in the background using background()
. For example, this creates a circle with a black stroke and blue fill:
Circle()
.strokeBorder(Color.black, lineWidth: 20)
.background(Circle().fill(Color.blue))
Using background()
ensures the blue circle always matches the size of the red circle.
The second option is to layer the two circles manually using ZStack
:
ZStack {
Circle()
.fill(Color.blue)
Circle()
.strokeBorder(Color.black, lineWidth: 20)
}
If you want to fill and stroke lots of shapes, you should consider wrapping up this functionality in an extension. Only InsettableShapes
get the strokeBorder()
method, so you should probably write two extension methods – one to handle regular shapes using stroke()
, and one to handle insettable shapes using strokeBorder()
.
Here’s how that looks in code:
extension Shape {
func fill<Fill: ShapeStyle, Stroke: ShapeStyle>(_ fillStyle: Fill, strokeBorder strokeStyle: Stroke, lineWidth: CGFloat = 1) -> some View {
self
.stroke(strokeStyle, lineWidth: lineWidth)
.background(self.fill(fillStyle))
}
}
extension InsettableShape {
func fill<Fill: ShapeStyle, Stroke: ShapeStyle>(_ fillStyle: Fill, strokeBorder strokeStyle: Stroke, lineWidth: CGFloat = 1) -> some View {
self
.strokeBorder(strokeStyle, lineWidth: lineWidth)
.background(self.fill(fillStyle))
}
}
SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.