1

Before asking my question, let me clarify 2 things first:

  1. I am developing an Android app
  2. 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 Matrix from this gradient, but then I don't know what to do next.
Sira Lam
  • 5,179
  • 3
  • 34
  • 68

1 Answers1

3

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

indrih17
  • 31
  • 4