Wednesday, March 05, 2008

Opposite color in the RGB palette

Recently I was working with a simple java code handling some colors. I had to display all the colors available in an image. I displayed the colors in the background and mentioned the color number as foreground. So, I got a beautiful rainbow of colors. The issue I faced is, to find the right foreground color for each item. I cannot fix a single color as the visibility will be affected when the background and foreground colors are same or similar.

Here I came across an interesting idea from the net, where the individual r,g,b components are bit-wise operated. Each of these three component numbers (ranging from 0 to 255) are toggled bitwise. A new color is formed and that will be complimentary to the original color.

This is what I wrote :


public static Color findOppositeColor(Color color)
{
if (color == null) return null;
int red = color.getRed();
red = findOppositeNumber(red);
int green = color.getGreen();
green = findOppositeNumber(green);
int blue = color.getBlue();
blue = findOppositeNumber(blue);
return new Color(red, green, blue);
}


public static int findOppositeNumber(int num)
{
// toggle the msb
return (num ^ 0x80) & 0xff;
}

Note: earlier I thought xoring all the bits is required, however I found that color #808080 failed to find the true opposite color as the xoring 0xff would return #7f7f7f, which is next color. Hence I had changed the logic to toggle only the most-significant-bit.

1 comment:

BoomSie said...

Stumbled upon the same problem today, I solved it with

return (~num) & 0xff;

Hope some peepz can use it