Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

swift - SwiftUI: How to draw filled and stroked shape?

In UIKit drawing a stroked & 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.

question from:https://stackoverflow.com/questions/56786163/swiftui-how-to-draw-filled-and-stroked-shape

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can also use strokeBorder and background combination.

code:

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

result :

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...