Java – Generating gradients programmatically


Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is this blog entry, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.

Best Answer

you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage p of the first colour and percentage 1 - p of the second:

R = firstCol.R * p + secondCol.R * (1 - p)

There's another question related to this.

There are other methods of interpolation that sometimes work better. For example, using a bell-shaped (sigmoidal) interpolation function makes the transition smoother.

/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.

In Java, you could use the GradientPaint.