How to create 2 overlapped connected rings in SwiftUI

Viewed 111

See below. It's not a simple overlay of two rings

enter image description here

1 Answers

Here is one way to do it. Use 2 .overlays redrawing the top half of the first (.orange) circle to have it overlap the second (.yellow) circle.

Overlapping rings running in simulator

Note: I added the ringColors, lineWidth, and scale as lets so that they can be easily experimented with:

struct ContentView: View {
    
    var body: some View {
        let ring1Color: Color = .orange
        let ring2Color: Color = .yellow
        let lineWidth: CGFloat = 40
        let scale: CGFloat = 0.7
        
        Circle()
            .scale(scale)
            .stroke(lineWidth: lineWidth)
            .foregroundColor(ring1Color)
            .offset(x: -lineWidth/2)
            .overlay(Circle()
                        .scale(scale)
                        .stroke(lineWidth: lineWidth)
                        .foregroundColor(ring2Color)
                        .offset(x: lineWidth/2))
            .overlay(Circle()
                        .trim(from: 0.5, to: 1)
                        .scale(scale)
                        .stroke(lineWidth: lineWidth)
                        .foregroundColor(ring1Color)
                        .offset(x: -lineWidth/2))
    }
}

Here I used .foregroundColor(.blue) for the last .overlay to reveal the magic. The drawing order is: 1) .orange, 2) .yellow, 3) .blue

Second overlay in blue to reveal drawing process

Related