Your First iOS & SwiftUI App: Polishing the App, Episode 20: Challenge: Draw the Rings | Kodeco

Try changing the color of the rings from black to a nice gradient.


This is a companion discussion topic for the original entry at https://www.kodeco.com/38052670-your-first-ios-swiftui-app-polishing-the-app/lessons/20

Hi there,

Iโ€™m trying to figure out how that this episode is working for the color grandient.

 ForEach(1..<6) { ring in
                let size = CGFloat(ring * 100)
                
                Circle()
                    .stroke(lineWidth: 20.0)
                    .fill(
                        RadialGradient(
                            colors: [Color("RingsColor").opacity(0.3 * 0.8), Color("RingsColor").opacity(0)],
                            center: .center,
                            startRadius: 100,
                            endRadius: 300
                        )
                    )
                    .frame(width: size, height: size)
            }

From that code alone I would expect that the gradient is applied per ring, meaning each circle starts of with a rings color and opacity 0.3 * 0.8, ending with an opacity of 0. However, This part alone applies to all rings so that only the outer ring is getting an opacity of 0, even though the fill is applied per ring and not for the whole container.

By playing around I found out that it has to do with the startRadius and endRadius, which would mean that there is only 1 gradient. But I donโ€™t really understand that because the gradient is again applied to each created circle.

I hope that my explanation is good enough to understand. Otherwise please ask, and thank you in advance!

Hi! Thanks for your question. I think youโ€™ve got a perfect understanding of how this is working! Each time through the ForEach, the same gradient is created and applied to the current ring. You can think of the ring shape a bit like a mask for each gradient. You only see the part of the gradient that each ring overlaps.

Another way to approach this to get a similar effect with out a gradient would be to make each ring a solid color, modifying the opacity based on the value of ring. You could do that by using ring as some kind of multiplier, or with a long if/else statement (or a switch statement, which we talk about in the Programming in Swift courses). That would be more like how the color in the Figma file works.

Hi Catie, thank you very much for your explanation! Thanks to that, I removed the stroke part to see if I understood the part with the โ€œmaskโ€, and I think I get it now or at least understand it much better :slight_smile:

1 Like