I have a list of colors in HEX format:
String[] validcolors = new String[]
{
"0055A5",
"101010",
"E4D200",
"FFFFFF",
"006563",
"A97B3E",
"B80000",
"6E3391",
"D191C3",
"D68200",
"60823C",
"AA8D73",
"73A1B8",
"6E6D6E",
"00582C",
"604421"
};
And a color object:
Color c = ...
I want to find the color that is closest to c
in validcolors
. Can somebody help me out? My initial idea was 'closest by RGB value', but whatever works is fine.
I would think of transforming the hex to .NET color then calculating somr sort of distance ((x2-x1)²+(y2-y1)²) and taking the closest using this distance:
string closestColor = "";
double diff = 200000; // > 255²x3
foreach(string colorHex in validColors)
{
Color color = System.Drawing.ColorTranslator.FromHtml("#"+colorHex);
if(diff > (diff = (c.R - color.R)²+(c.G - color.G)²+(c.B - color.B)²))
closestColor = colorHex;
}
return closestColor;
The distance between two colors depends on the color model you are using. See this article in the Wikipedia so until we know what model you prefer we can't help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With