Contrasting Colours in C#

It’s still not perfect … but this is a bit of code another developer and I came up with a while ago for finding contrasting colours.


/// <summary>
/// From a given colour it works out a suitable colour that will sit on top of
/// it so that the contrast is suitable for readability.
/// </summary>
/// <param name="baseColor">Color to get the contrasting complement of</param>
/// <returns>Contrasting color</returns>
public static Color GetContrastingColor(Color baseColor)
{
HSB baseHsb = ColorToHsb(baseColor);
int newSaturation = baseHsb.Saturation;
int newBrightness = baseHsb.Brightness;

if ((baseHsb.Saturation >= 40 && baseHsb.Saturation <= 60) && (baseHsb.Brightness >= 40 && baseHsb.Brightness <= 60))
{
newSaturation = (baseHsb.Saturation <= 50 ? 100 : 0);
newBrightness = (baseHsb.Brightness <= 50 ? 100 : 0);
}
else if (baseHsb.Saturation >= 40 && baseHsb.Saturation <= 60)
{
newSaturation = (baseHsb.Saturation <= 50 ? 100 : 0);
}
else if (baseHsb.Brightness >= 40 && baseHsb.Brightness <= 60)
{
newBrightness = (baseHsb.Brightness <= 50 ? 100 : 0);
}
else
{
newSaturation = 100 - baseHsb.Saturation;
newBrightness = 100 - baseHsb.Brightness;
}

if (baseHsb.Saturation == 0)
{
newSaturation = 0;
}

HSB newHsb = new HSB(baseHsb.Hue, newSaturation, newBrightness);
return HsbToColor(newHsb);
}