10

I have 60% Opaque form. And when the user changes the color of the form, sometimes (depending on the chosen color), they cannot see the text on the form anymore because it too-closely resembles the color of the form. So, I'm trying to do maybe an if/switch to see if the chosen BackColor of the form is either Dark, or Light. If it is Dark, then all text on the form should be White. If it is Light, then all text on the form should be Black.

Is this at all possible? I've seen this all over the place but not sure what to search for without writing the whole question in the search field.

Any help/suggestions would be greatly appreciated.

Thanks, jason.

jay_t55
  • 10,203
  • 26
  • 92
  • 167

3 Answers3

23

How about using Color.GetBrightness() to work out how light it is?

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
9

You could check, if the sum of the three rgb-values are above the half of the max-value

-> because 255,255,255 == white(light) and 0,0,0 == black(dark) :

f.e.

R 255
G 140
B 170
=====
  565

Max: 765 (Middle 382) Sum: 565

Because the sum is 565 and above the middle (dark < 382 < light), the color is light. So you can change the textcolor to dark.

BvuRVKyUVlViVIc7
  • 11,200
  • 8
  • 55
  • 105
5

This method checks whether the contrast of two colors is readable:

public static bool ContrastReadableIs(Color color_1, Color color_2)
{
    // Maximum contrast would be a value of "1.0f" which is the brightness
    // difference between "Color.Black" and "Color.White"
    float minContrast = 0.5f;

    float brightness_1 = color_1.GetBrightness();
    float brightness_2 = color_2.GetBrightness();

    // Contrast readable?
    return (Math.Abs(brightness_1 - brightness_2) >= minContrast);
}

Having a backcolor looking for a readable forecolor?
Here is a simple and quite good approach to invert the backcolor.
NB: This invertation does not mean that color and inverted color differ in brightness, but if two colors differ in brightness at least 0.5 they usually show a readable contrast.

Button with text "Am I readable?"

Test code for click handler button1

Random r = new Random();

while (1 < 2)
{
    // Get a random fore- and backcolor
    Color foreColor = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256));
    Color backColor = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256));

    // Contrast readable?
    if (ContrastReadableIs(foreColor, backColor))
    {
        button1.ForeColor = foreColor;
        button1.BackColor = backColor;
        System.Media.SystemSounds.Beep.Play();
        break;
    }
}
Community
  • 1
  • 1
Pollitzer
  • 1,456
  • 2
  • 16
  • 26