'How to get a color in a certain point of a linear gradient, in Java / Kotlin / Android?
Before asking my question, let me clarify 2 things first:
- I am developing an Android app
- I do not need nor want to draw the gradient. I just want to know the color.
Question
I have 2 colors, let's name them startColor and endColor.
Now please imagine a linear gradient line from startColor to endColor.
Let's say I have a float 0.3f.
I want to know at the 30% position, from start to end, the color at the gradient.
How can I do this?
Things I have tried
- Java awt library's
GradientPaint- It is not available in Android context; - android.graphics.LinearGradient - The best I can do is to get a
Matrixfrom this gradient, but then I don't know what to do next.
Solution 1:[1]
You simply linearly interpolate the red, the green, and the blue colors like this:
fun pointBetweenColors(from: Float, to: Float, percent: Float): Float =
from + percent * (to - from)
fun pointBetweenColors(from: Color, to: Color, percent: Float) =
Color(
red = pointBetweenColors(from.red, to.red, percent),
green = pointBetweenColors(from.green, to.green, percent),
blue = pointBetweenColors(from.blue, to.blue, percent),
alpha = pointBetweenColors(from.alpha, to.alpha, percent),
)
where percent is a value between 0 and 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | indrih17 |
