I'm trying to make a gradient effect. I want to make a method that returns returns a color for a position on a gradient. So for example, if variable "x" can be anything from 0 to 9, if x was 0 I might want the method to return black. If x was 9, I might want it to return white, and if x was 2 I mighy want the function to return a dark gray. The colors don't have to be white and black, but any two colors. (The method would return a "Color" from the Java Color class)

I tried to make a weighted average for each rgb value and put them back together, but it doesn't work properly. The colors don't mix properly

Oh... I put in "return new Color( (r << 16) | (g << | b )" and it worked. Huh... I had only read about these bit-wise operators and never used them. I wonder why my implementation didn't work... Oh well, probably just messed up the math. Anyway, it works now. Thanks!

An int can hold 32 bits of data. 32 bits == 4 bytes. Which further equals 1 int (I.e, an int is made up of 4 bytes).

A pixel/color is a bucket of data that holds 3 colours: Red, Green and Blue. Why? Because using those 3 colours we can trick the human eye to see over 16 million different colours (255 * 255 * 255).

So because an int can hold up to 4 bytes a pixel is usually represented as an int. Sometimes the last byte is used for transparency (Alpha).

You are saving the r, g and b values as ints which make them all look something like this:

0000 0000 0000 0000 0000 0000 0000 0000

With the last first (bits are read from right to left) 2 bytes (8 bits) actually representing the given colour value (0-255).

So to pack them all together into 1 int you need to combine the bits and shift the Red colour 2 bytes (16 bits) to the left and the Green byte 1 byte (8 bits) to the left using the universal bitwise or operator so that you get them in the nice RGB order.

I tried to make a weighted average for each rgb value and put them back together, but it doesn't work properly. The colors don't mix properly

No, RGB isn't a very good colour space for interpolation. If you want to keep it simple, you could use HSV and Java's built-in conversions between RGB and HSV [1]; otherwise you can either explore JAI (might have some useful stuff - I haven't looked) or write some conversion code to and from La*b*, perhaps porting it from http://www.codeproject.com/Articles/19045/Manipulating-colors-in-NET-Part-1

This is important. Take, for example, converting to grayscale. A simple linear interpolation might do something like ((r+g+b)/255.0*3) * 255 and set all the r/g/b components to that value. It ends up looking like crap.

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org