What is the best way to convert a System.Drawing.Color
to a similar System.ConsoleColor
?
Easy one...
Public Shared Function ColorToConsoleColor(cColor As Color) As ConsoleColor
Dim cc As ConsoleColor
If Not System.Enum.TryParse(Of ConsoleColor)(cColor.Name, cc) Then
Dim intensity = If(Color.Gray.GetBrightness() < cColor.GetBrightness(), 8, 0)
Dim r = If(cColor.R >= &H80, 4, 0)
Dim g = If(cColor.G >= &H80, 2, 0)
Dim b = If(cColor.B >= &H80, 1, 0)
cc = CType(intensity + r + g + b, ConsoleColor)
End If
Return cc
End Function
A simple and effective approach can be implemented by using the GetHue
, GetBrightness
and GetSaturation
methods of the Color
class.
public static ConsoleColor GetConsoleColor(this Color color) {
if (color.GetSaturation() < 0.5) {
// we have a grayish color
switch ((int)(color.GetBrightness()*3.5)) {
case 0: return ConsoleColor.Black;
case 1: return ConsoleColor.DarkGray;
case 2: return ConsoleColor.Gray;
default: return ConsoleColor.White;
}
}
int hue = (int)Math.Round(color.GetHue()/60, MidpointRounding.AwayFromZero);
if (color.GetBrightness() < 0.4) {
// dark color
switch (hue) {
case 1: return ConsoleColor.DarkYellow;
case 2: return ConsoleColor.DarkGreen;
case 3: return ConsoleColor.DarkCyan;
case 4: return ConsoleColor.DarkBlue;
case 5: return ConsoleColor.DarkMagenta;
default: return ConsoleColor.DarkRed;
}
}
// bright color
switch (hue) {
case 1: return ConsoleColor.Yellow;
case 2: return ConsoleColor.Green;
case 3: return ConsoleColor.Cyan;
case 4: return ConsoleColor.Blue;
case 5: return ConsoleColor.Magenta;
default: return ConsoleColor.Red;
}
}
Note that the color names of the console do not match the well known colors. So if you test a color mapping scheme, you have to keep in mind that (for instance) in the well known colors, Gray is dark gray, Light Gray is gray, Green is dark green, Lime is pure green, and Olive is dark yellow.