Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How to draw filled and stroked shape?

Tags:

swift

swiftui

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.

like image 404
orj Avatar asked Jun 27 '19 07:06

orj


People also ask

How do you make a rounded rectangle in SwiftUI?

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.

How do I add a border to a circle in SwiftUI?

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!")


2 Answers

You can also use strokeBorder and background in combination.

Code:

Circle()     .strokeBorder(Color.blue,lineWidth: 4)     .background(Circle().foregroundColor(Color.red)) 

Result:

like image 160
Burak Dizlek Avatar answered Sep 21 '22 12:09

Burak Dizlek


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))    } } 

circle with stroked border

like image 28
Imran Avatar answered Sep 22 '22 12:09

Imran