Reputation: 1527
I'm trying to create a gradient using the same color with a brightness modifier at one end. I tried this:
let gradient = LinearGradient(
colors: [Color.blue, Color.blue.brightness(0.1)],
startPoint: .top, endPoint: .bottom)
Unfortunately this does not compile with the following error: Cannot convert value of type 'some View' to expected element type 'Array<Color>.ArrayLiteralElement' (aka 'Color')
According to this thread I would have expected it to work. How can I fix this?
Upvotes: 2
Views: 1706
Reputation: 1427
You cannot use brightness(_:)
modifier here. It returns View
instead of Color
.
If you want to add brightness to Color, you may need help from UIKit and need to implement as below.
extension Color {
func adjust(hue: CGFloat = 0, saturation: CGFloat = 0, brightness: CGFloat = 0, opacity: CGFloat = 1) -> Color {
let color = UIColor(self)
var currentHue: CGFloat = 0
var currentSaturation: CGFloat = 0
var currentBrigthness: CGFloat = 0
var currentOpacity: CGFloat = 0
if color.getHue(¤tHue, saturation: ¤tSaturation, brightness: ¤tBrigthness, alpha: ¤tOpacity) {
return Color(hue: currentHue + hue, saturation: currentSaturation + saturation, brightness: currentBrigthness + brightness, opacity: currentOpacity + opacity)
}
return self
}
}
Then you can use it like this.
LinearGradient(
colors: [
Color.blue.adjust(brightness: 0.5),
Color.blue,
Color.blue.adjust(brightness: -0.5),
],
startPoint: .top,
endPoint: .bottom
)
You can also use this initializer Color(hue:saturation:brightness:opacity:)
for your custom color.
Upvotes: 8
Reputation: 257711
The brightness
modifier creates a view, not a color. A possible solution is to use Color with HSB initialiser, like below
let gradient = LinearGradient(
colors: [Color.blue, Color(hue: 229/360, saturation: 0.98, brightness: 0.1)],
startPoint: .top, endPoint: .bottom)
Upvotes: 2