简体   繁体   中英

Change Control's Text Color Depending on Control's Background Color

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?

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;

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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM