Converting Color to ConsoleColor?

前端 未结 8 1349
面向向阳花
面向向阳花 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:42

    Unfortunately, even though the Windows console can support RGB colors, the Console class only exposes the ConsoleColor enumeration which greatly limits the possible colors you can use. If you want a Color structure to be mapped to the "closest" ConsoleColor, that will be tricky.

    But if you want the named Color to match a corresponding ConsoleColor you can make a map such as:

    var map = new Dictionary();
    map[Color.Red] = ConsoleColor.Red;
    map[Color.Blue] = ConsoleColor.Blue;
    etc...
    

    Or if performance is not that important, you can round trip through String. (Only works for named colors)

    var color = Enum.Parse(typeof(ConsoleColor), color.Name);
    

    EDIT: Here's a link to a question about finding color "closeness".

提交回复
热议问题