tags:

views:

387

answers:

4

I am trying to make a color change on a canvas in java to respresent how strong or weak the values respresented by color are relative to each other.

The rgb colors have to be the same color just different shades, like white to grey to black and every shade of grey in between. How can I change the rgb values considering that the values I am representing vary a lot, from -9999999 to positive 9999999.

A: 

I'm not completely sure I understand your question, but, if I do:

Why not just scale the RGB values to the values in your range (from -9999999 to positive 9999999)? Moreover, set R, G, and B all to the same value so that you're using shades of gray to represent the value.

Like this:

private final int MIN = -9999999;
private final int MAX = 9999999;

public Color getScaledColor(int val) {
 int gray = (int) Math.round((double) (val - MIN) / (double) (MAX - MIN)
   * 255.0);
 Color color = new Color(gray, gray, gray);

 return color;
}

Note that this solution will not give unique colors for all the values in the range you specified. But also keep in mind that the human eye can only distinguish between so many shades (and 2 * 9999999 + 1 is probably more than the number of shades than it can distinguish between).

Paul Reiners
+2  A: 
Vineet Reynolds
This is probably what you want. Paul's solution will work, but only give you 255 different grays, and getting more of them is easiest to do in another color spaces like HSV
Mongoose
+2  A: 

Yes, scale your values to fit your domain. That depends on how your RGB values are stored. Usually, 8 bits are used for each. Since grey has R = G = B, you want to scale values in range (-9999999,9999999) to (0, 255).

Consider x in the first interval. Since the first range covers also negative numbers, first, do a shift.

x = x + 9999999

Now x is in the interval (0, 19999998). And the next step is to scale it down to (0, 255). Since the colour values grow linearly in that interval, all you have to do is this:

x = x * 255 / 19999998

Now x is in the interval (0, 255) just like you want.

Generally, if your inital values are in an interval (a, b) and want to transform it into (0, c), apply this formula: (Note that a can be negative)

x = (x - a) * c / (b - a)

So if you R, G, B values are 16 bits long, c will be 2**16 = 65536 and the formula:

x = (x + 9999999) * 65536 / 19999998

Hope that helps.

Andrei Vajna II
A: 

The HSL Color class implements the formulas provided in the Wikipedia link on HSL/HSV provide above.

camickr