In UIKit drawing a stroked and filled path/shape is pretty easy.
Eg, the code below draws a red circle that is stroked in blue.
override func draw(_ rect: CGRect) { guard let ctx = UIGraphicsGetCurrentContext() else { return } let center = CGPoint(x: rect.midX, y: rect.midY) ctx.setFillColor(UIColor.red.cgColor) ctx.setStrokeColor(UIColor.blue.cgColor) let arc = UIBezierPath(arcCenter: center, radius: rect.width/2, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true) arc.stroke() arc.fill() }
How does one do this with SwiftUI?
Swift UI seems to support:
Circle().stroke(Color.blue) // and/or Circle().fill(Color.red)
but not
Circle().fill(Color.red).stroke(Color.blue) // Value of type 'ShapeView<StrokedShape<Circle>, Color>' has no member 'fill' // or Circle().stroke(Color.blue).fill(Color.red) // Value of type 'ShapeView<Circle, Color>' has no member 'stroke'
Am I supposed to just ZStack two circles? That seems a bit silly.
Any SwiftUI view can have its corners rounded using the cornerRadius() modifier. This takes a simple value in points that controls how pronounced the rounding should be.
To change that, and make the shape view act as a border, all we have to do is to apply a stroke to it, passing as argument the desired color. Text("Borders in SwiftUI!") Text("Borders in SwiftUI!") Text("Borders in SwiftUI!")
You can also use strokeBorder
and background
in combination.
Circle() .strokeBorder(Color.blue,lineWidth: 4) .background(Circle().foregroundColor(Color.red))
You can draw a circle with a stroke border
struct ContentView: View { var body: some View { Circle() .strokeBorder(Color.green,lineWidth: 3) .background(Circle().foregroundColor(Color.red)) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With