2

I have a TextBox that displays a color as its background color and the background color code in its text. I have set the text color as Black.

The problem is that if the user sets the color as Black then the color code will be unreadable. How do I set the text color programmatically so that it becomes readable when the user selects any color?

Elmo
  • 6,409
  • 16
  • 72
  • 140
  • 1
    Check out [this article](http://www.splitbrain.org/blog/2008-09/18-calculating_color_contrast_with_php) and the posted example. It's in php but the concept can be transferred to c# very easily. – Bala R Sep 21 '11 at 18:04
  • 1
    http://stackoverflow.com/questions/1165107/how-do-i-invert-a-colour/1165145#1165145 – Tim Schmelter Sep 21 '11 at 18:07

2 Answers2

5

You can use negative color for the text:

Color InvertColor(Color sourceColor) {
    return Color.FromArgb(255 - sourceColor.R, 
                          255 - sourceColor.G,
                          255 - sourceColor.B);
}

Any color is guaranteed to be more or less readable on its negative color, so there you go. This is a quick and dirty way to invert a color, you may also want to check the answers for this question: How do I invert a color?

Another option is to add a white halo to the black text. That's what people do in GIS applications to ensure that map labels are readable on top of any surface. The idea of halo effect is to have a thin white border around black text. This way the text is readable whether it's on white background (the border becomes invisible) or on black background (the border outlines the text).

There are multiple tutorials on the topic, like this article or this SO question (with VB.NET sample).

When you have a Color picked out, just assign it to the ForeColor property of your textbox like this:

txtColor.ForeColor = mycolor;
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
Dyppl
  • 12,161
  • 9
  • 47
  • 68
2

Not working on Gray color.

This code is more usable:

 lblCarColor.BackColor = color;
 if ((color.B + color.R + color.G) / 3 <= 128)
 {
     lblCarColor.ForeColor = Color.White;
 }
David
  • 21
  • 2