Kyranstar
Kyranstar

Reputation: 1720

Filling a Color Array with a Gradient

I'm trying to generate with code a one dimensional array of Color in java with a gradient of color, how can I do this? I also want to be able to use multiple colors in the gradient.

I want it to be sort of like this: Linear gradient

Upvotes: 5

Views: 2803

Answers (1)

Krease
Krease

Reputation: 16215

Let's break this down into some generic steps:

  1. Figure out what the RGB values for startColor and endColor are. For example, perhaps they are (64, 128, 192) and (255, 255, 255)
  2. Figure out how many steps in your color gradient you want. Based on your question, it looks like you want 100 steps. You probably don't need 100, though it depends on what you want to do with it I suppose.
  3. Figure out the difference between each color value - in my example, it's (191, 127, 63).
  4. Now you know how much to change each value for each loop iteration: (191/100, 127/100, 63/100).
  5. Create a loop that starts with your startColor, applies (rounded) change to the color values each iteration, adding each new Color to your array. At the end of your loop, the last Color added will end up being the endColor

Voila - there's your array of Color objects representing your gradient.

If you want, you should be able to figure out how to extend this to a multi-color gradient (red -> yellow -> green) as well, simply by creating two loops that transition to each color.

Upvotes: 7

Related Questions