Stoic
Stoic

Reputation: 1216

SwiftUI: Gradient fill not showing up

The following code produces a Rectangle() that is white and un-filled. I have zero ideas why, and I'm not getting any errors.

Note: When I replace the custom colors (i.e. Color(red: green: blue:) with built-in colors such as Color.red or Color.blue, fill shows up and is colored.

var body: some View {
        Rectangle()
            .fill(
                LinearGradient(
                    colors: [Color(red: 180, green: 40, blue: 55),
                             Color(red: 200, green: 40, blue: 55)],
                    startPoint: .top,
                    endPoint: .bottom)
            )
    }

What's making the fill not show up, and how can I fix this while keeping my custom colors?

Upvotes: 1

Views: 775

Answers (1)

ScottM
ScottM

Reputation: 10424

The Color initializer you're using defines the color using the sRGB color space and clamps any supplied component values to between 0 and 1. So supplying any value greater than 1 for all three values will create a white color - the equivalent of Color(red: 1.0, green: 1.0, blue: 1.0).

To get the colors you need, you should divide each value by 255, e.g.:

colors: [Color(red: 0.706, green: 0.157, blue: 0.216),
         Color(red: 0.784, green: 0.157, blue: 0.216)],

See the Apple documentation.

Upvotes: 3

Related Questions