How to draw a border inside a view
How to draw a border inside a view êŽë š
Updated for Xcode 15
SwiftUI gives us both stroke()
and strokeBorder()
modifiers for drawing borders around shapes, and they have subtly different behavior:
- The
strokeBorder()
modifier insets the view by half your border width then applies the stroke, meaning that the entire border is drawn inside the view. - The
stroke()
modifier draws a border centered on the viewâs edge, meaning that half the border is inside the view and half outside.
Important
Both of these modifiers only apply to shapes â you can use stroke()
and strokeBorder()
with Circle
, Rectangle
, Capsule
, and so on, but not with Text
, Image
or other non-shape views. If you want to draw a border around non-shape views, you should use the border()
modifier instead â see âHow to draw a border around a viewâ.
If you want to see strokeBorder()
in action, try this:
Circle()
.strokeBorder(.blue, lineWidth: 50)
.frame(width: 200, height: 200)
.padding()
Because that uses strokeBorder()
, the 50-point blue stroke will be drawn entirely inside the circle.
If you arenât quite sure of the difference from stroke()
, try changing your code to this:
Circle()
.stroke(.blue, lineWidth: 50)
.frame(width: 200, height: 200)
.padding()
Now youâll see the circle looks bigger because the stroke is drawn half inside and half outside the circle.