Contrast

The Color Pro package includes several functions for getting the contrast ratio between colors. This is primarily used when determining accessibility requirements, but it can also be used for other purposes.


🔲 Calculating Contrast

Contrast functions are declared as extension methods in the static class Contrast.

Color foreground = Color.white;
Color background = Color.black;

float contrast = foreground.ContrastRatio(background);

The calculation itself is as follows:

public static float ContrastRatio(this Color color, Color other)
{
    float luminanceA = color.RelativeLuminance();
    float luminanceB = other.RelativeLuminance();

    float darker = Mathf.Min(luminanceA, luminanceB);
    float lighter = Mathf.Max(luminanceA, luminanceB);

    return (lighter + 0.05f) / (darker + 0.05f);
}

🔳 Higher / Lower

Sometimes it is useful to find the color that has the highest or lowest contrast ratio to many other colors. For example, if your background color is blue you can determine if white text or black text would be more readable.

Color background = Color.blue;
Color foreground = background.HigherContrastingColor(Color.white, Color.black);