in my current tool there is a colored box with some numbers in it. The backcolor of the box is defined by some sort of list but can also be altered by the user. The forecolor (== fontcolor of the numbers) cannot, and i want to make sure that the user can always read the numbers, so i´d like to adjust the forecolor of the numbers anytime the backcolor changes.
Atm i use code like this:
if(Math.Abs(foreColor.GetBrightness() - backColor.GetBrightness()) <= 0.5f)
{
if(foreColor.GetBrightness() > 0.5f开发者_如何学Python)
{
foreColor = Color.Black;
}
else
{
foreColor = Color.White;
}
}
but that is only a workaround for the problem, there are quite a lot of colors (mostly yellows) leading to a bad to read display. Anyone touched a similar problem and found a good solution?
For each color component (assume a range of [0, 255] per component), if it's below 128, saturate it to 255; otherwise make it zero:
fg.r = bg.r < 128 ? 255 : 0;
fg.g = bg.g < 128 ? 255 : 0;
fg.b = bg.b < 128 ? 255 : 0;
This will essentially place the foreground color as far into the octant opposite the background color as possible.
Here is another way to do this, while using only black and white as forecolor:
foreColor = Color.Black;
int changeToWhite = 0;
if(backColor.R <= 128)
{
changeToWhite++;
}
if(backColor.G <= 128)
{
changeToWhite++;
}
if(backColor.B <= 128)
{
changeToWhite++;
}
if(changeToWhite > 1)
{
foreColor = Color.White;
}
Notice the slight adjustment: <= This ensures the calculated color will be white in cases in some "close calls" you get from the default windows color picker.
This one works perfectly.
gray = ((backColor.R*38 + backColor.G*75 + backColor.B*15) >> 7);
foreColor = gray < 128 ? Color.White : Color.Black;
精彩评论