Skip to content

Instantly share code, notes, and snippets.

@i-e-b
Created June 22, 2022 10:27
Show Gist options
  • Save i-e-b/08ace93c73a61619ed640367b3ca4a5a to your computer and use it in GitHub Desktop.
Save i-e-b/08ace93c73a61619ed640367b3ca4a5a to your computer and use it in GitHub Desktop.
Write colors to dotnet console
static int[] cColors = { 0x000000, 0x000080, 0x008000, 0x008080, 0x800000, 0x800080, 0x808000, 0xC0C0C0, 0x808080, 0x0000FF, 0x00FF00, 0x00FFFF, 0xFF0000, 0xFF00FF, 0xFFFF00, 0xFFFFFF };
/// <summary>
/// By Antonín Lejsek https://stackoverflow.com/a/33715138/423033
/// </summary>
/// <param name="cValue"></param>
public static void ConsoleWritePixel(Color cValue)
{
Color[] cTable = cColors.Select(Color.FromArgb).ToArray();
char[] rList = { (char)9617, (char)9618, (char)9619, (char)9608 }; // 0, 1/4, 2/4, 3/4, 4/4
int[] bestHit = { 0, 0, 4, int.MaxValue }; //ForeColor, BackColor, Symbol, Score
for (int rChar = rList.Length; rChar > 0; rChar--)
{
for (int cFore = 0; cFore < cTable.Length; cFore++)
{
for (int cBack = 0; cBack < cTable.Length; cBack++)
{
int R = (cTable[cFore].R * rChar + cTable[cBack].R * (rList.Length - rChar)) / rList.Length;
int G = (cTable[cFore].G * rChar + cTable[cBack].G * (rList.Length - rChar)) / rList.Length;
int B = (cTable[cFore].B * rChar + cTable[cBack].B * (rList.Length - rChar)) / rList.Length;
int iScore = (cValue.R - R) * (cValue.R - R) + (cValue.G - G) * (cValue.G - G) + (cValue.B - B) * (cValue.B - B);
if (!(rChar > 1 && rChar < 4 && iScore > 50000)) // rule out too weird combinations
{
if (iScore < bestHit[3])
{
bestHit[3] = iScore; //Score
bestHit[0] = cFore; //ForeColor
bestHit[1] = cBack; //BackColor
bestHit[2] = rChar; //Symbol
}
}
}
}
}
Console.ForegroundColor = (ConsoleColor)bestHit[0];
Console.BackgroundColor = (ConsoleColor)bestHit[1];
Console.Write(rList[bestHit[2] - 1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment