Search code examples
swiftuilinear-gradients

Make the soft gradient between colors of LinearGradient removed


Let's say I have a LinearGradient of 3 colors Red, Blue, and Green.

Can we possibly make the soft gradient between these 3 colors removed? I am trying to animate between hard and soft gradient of LinearGradient.

Something like this:

LinearGradient(colors: [.red, .blue, .green], startPoint: .trailing, endPoint: .leading)

what i have: enter image description here

what i want it to be when some condition is met: enter image description here


Solution

  • You can use LinearGradient(stops: ) init. It will not give you a full hard edge, but quite close. You can then change the stop values or the array for animation.

    enter image description here

    struct ContentView: View {
        
        let stops = [Gradient.Stop(color: Color.green, location: 0.0),
                     Gradient.Stop(color: Color.green, location: 0.33),
                     Gradient.Stop(color: Color.blue, location: 0.33),
                     Gradient.Stop(color: Color.blue, location: 0.66),
                     Gradient.Stop(color: Color.red, location: 0.66),
                     Gradient.Stop(color: Color.red, location: 1.0)]
    
        var body: some View {
            Rectangle()
                .fill(
                    LinearGradient(stops: stops, startPoint: .trailing, endPoint: .leading)
                )
                .frame(height: 200)
                .padding()
        }
    }