I have a user setup where they can choose the colors of the alerts. the Alert is the background color on a text or button. But the problem comes in that if they select a dark blue and we have black letters the contrast isnt enough and you cannot read it.
I have tried to make a function to get the reverse opposing color but havent got too far.
Is there such a function?
Red and green cancel each other as do yellow and blue. They further reasoned that if one started with a color such as bluish green it should be possible to mix this color with a unique yellow to cancel out the blue content leaving only green. This is the basic idea behind the hue cancellation technique.
Color inversion is a photo effect that flips all colors to their opposite hue on the color wheel. For example, white becomes black, green becomes magenta, and blue becomes orange.
Finding a complementary color is very simple in the RGB model. For any given color, for example, red (#FF0000), you need to find the color, which, after being added to red, creates white (0xFFFFFF). Naturally, all you need to do, is subtract red from white and get cyan (0xFFFFFF - 0xFF0000 = 0x00FFFF).
I found that the best solution for me is to convert the RGB values into YIQ values. As we are only interested in the brightness value (represented by Y), there is one single calculation to be done: Y = (299*R + 587*G + 114*B)/1000
. The Java code for that would look like this:
public static Color getContrastColor(Color color) {
double y = (299 * color.getRed() + 587 * color.getGreen() + 114 * color.getBlue()) / 1000;
return y >= 128 ? Color.black : Color.white;
}
You can see that it simply decides to use black or white, based upon the brightness of the original color. And the result works very nice in my opinion. The weights (299, 587, 114) are proportional to the sensitivity of the eyes (or rather the sensitivity of the retina) to the corresponding color.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With