Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically find complement of colors?

Tags:

java

colors

Is there a way to find the complement of a color given its RGB values? Or can it only be found for certain colors? How would someone go about doing this in Java?

like image 909
Mohit Deshpande Avatar asked Jun 16 '10 15:06

Mohit Deshpande


People also ask

What colours are complements?

Examples of complementary color combinations are: Red and green; yellow and purple; orange and blue; green and magenta. Complementary color combos tend to be bold, which is why sports teams often use this formula for their colors.

Do blue and yellow complement each other?

Complementary colors are pairs of colors, diametrically opposite on a color circle: as seen in Newton's color circle, red and green, and blue and yellow. Yellow complements blue; mixed yellow and blue lights generate white light.

What are complementary Colours in computer graphics?

Complementary colors are pairs of colors which, when combined or mixed, cancel each other out (lose hue) by producing a grayscale color like white or black. When placed next to each other, they create the strongest contrast for those two colors. Complementary colors may also be called "opposite colors".


3 Answers

This is what I come up: (Conjecture)

Let r, g, and b be RGB components of the original color.

Let r', g', and b' be RGB components of the complementary color.

Then:

r' = max(r,b,g) + min(r,b,g) - r   
b' = max(r,b,g) + min(r,b,g) - b
g' = max(r,b,g) + min(r,b,g) - g

I see that this gives the same answer to what the websites (i.e. www.color-hex.com) give, but I will still prove it. :)

like image 136
Poypoyan Avatar answered Sep 28 '22 11:09

Poypoyan


A more general and simple solution for finding the opposite color is:

private int getComplementaryColor( int color) {
    int R = color & 255;
    int G = (color >> 8) & 255;
    int B = (color >> 16) & 255;
    int A = (color >> 24) & 255;
    R = 255 - R;
    G = 255 - G;
    B = 255 - B;
    return R + (G << 8) + ( B << 16) + ( A << 24);
}
like image 25
tm1701 Avatar answered Sep 28 '22 11:09

tm1701


For a rough approximation, you can do this by converting RGB to HSL (Hue, Saturation, Lightness).

With the HSL value, shift the hue 180 degrees to get a color on the opposite of the color wheel from the original value.

Finally, convert back to RGB.

I've written a JavaScript implementation using a hex value here - https://stackoverflow.com/a/37657940/4939630

For RGB, simply remove the hex to RGB and RGB to hex conversions.

like image 45
Edward Avatar answered Sep 28 '22 10:09

Edward