C # Round color in colors listed

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 color object:

 Color c = ... 

I want to find the color that is closest to c in validcolors . Can someone help me? My original idea was “closest to the RGB value”, but everything worked fine.

+4
source share
3 answers

I would think about converting the hexagon to .NET color, and then calculate the somr type of distance ((x2-x1) ² + (y2-y1) ²) and get as close to that distance as possible:

 string closestColor = ""; double diff = 200000; // > 255²x3 foreach(string colorHex in validColors) { Color color = System.Drawing.ColorTranslator.FromHtml("#"+colorHex); if(diff > (diff = (cR - color.R)²+(cG - color.G)²+(cB - color.B)²)) closestColor = colorHex; } return closestColor; 
+6
source

The distance between the two colors depends on the color model you are using. See this Wikipedia article until we find out which model you prefer, we cannot help.

+2
source

Uses the (verbose) method using HSB.

 float targetHue = c.GetHue(); float targetSat = c.GetSaturation(); float targetBri = c.GetBrightness(); string closestColor = ""; double smallestDiff = double.MaxValue; foreach (string colorHex in validcolors) { Color currentColor = ColorTranslator.FromHtml("#" + colorHex); float currentHue = currentColor.GetHue(); float currentSat = currentColor.GetSaturation(); float currentBri = currentColor.GetBrightness(); double currentDiff = Math.Pow(targetHue - currentHue, 2) + Math.Pow(targetSat - currentSat, 2) + Math.Pow(targetBri - currentBri, 2); if (currentDiff < smallestDiff) { smallestDiff = currentDiff; closestColor = colorHex; } } return closestColor; 
0
source

Source: https://habr.com/ru/post/1346436/


All Articles