Reverse opposing colors C#, Java

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?


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.white;

Code C#

public static Color GetContrastColor(Color color)
            double y = (double)(299 * color.R + 587 * color.G + 114 * color.B) / 1000;
            return y >= 128 ? Color.Black : Color.White;

How to use

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#3399cc");
var c = GetContrastColor(col);
 return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");