Converting Color to ConsoleColor?

前端 未结 8 1357
面向向阳花
面向向阳花 2020-12-02 21:22

What is the best way to convert a System.Drawing.Color to a similar System.ConsoleColor?

8条回答
  •  悲&欢浪女
    2020-12-02 21:51

    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.

提交回复
热议问题