C# remove darker colors from KnownColor
I got a list of Knowncolor from the system but I want to remove some which are 开发者_开发技巧too dark and make the foreground character unseen. I tried the following code but KnownColor.Black still shows up. Is there anyway to order them by their darkness?
if (knownColor > KnownColor.Transparent && knownColor < KnownColor.MidnightBlue && knownColor < KnownColor.Navy)
{
//add it to our list
colors.Add(knownColor);
}
You can convert the known colors to a Color instance and then compare brightness using the GetBrightness()
method:
Gets the hue-saturation-brightness (HSB) brightness value for this Color structure. The brightness ranges from 0.0 through Blockquote 1.0, where 0.0 represents black and 1.0 represents white.
float brightness = Color.FromKnownColor(KnownColor.Transparent).GetBrightness();
Applied to your example, something like the following should work (tested for black and yellow):
KnownColor knownColor = KnownColor.Yellow;
float transparentBrightness = Color.FromKnownColor(KnownColor.Transparent).GetBrightness();
float midnightBlueBrightness = Color.FromKnownColor(KnownColor.MidnightBlue).GetBrightness();
float navyBrightness = Color.FromKnownColor(KnownColor.Navy).GetBrightness();
float knownColorBrightness = Color.FromKnownColor(knownColor).GetBrightness();
if (knownColorBrightness < transparentBrightness
&& knownColorBrightness > midnightBlueBrightness
&& knownColorBrightness > navyBrightness)
{
//add it to our list
colors.Add(knownColor);
}
Take a look at my answer regarding determining a foreground color - it involves calculating the perceived brightness of the background color to decide whether to display white or black as a foreground. You could use the same method and simply choose to eliminate the colors too dark:
Make foregroundcolor black or white depending on background
精彩评论