Let's say I have an array with colors (with the whole color spectrum, from red to red.). A shorter version would look like this:
public Color[] ColorArray = new Color[360] { Color.FromArgb(255, 245, 244, 242), Color.FromArgb(255, 245, 244, 240), Color.FromArgb(255, 245, 244, 238) }
Now if I have a seperate
Color object (Color c = Color.FromArgb(255, 14, 4, 5))
How can I get the value in the Array that is the closest to the selected color? And is this even possible?
Try this:
here I interpret
closest
as Euclidean distance in ARGB spaceColor distance is not a precisely defined thing. So here are three methods to measure it:
Obviously you may want to change the magic numbers in the 3rd measurement: hue is in 0-360, brightness and saturation are in 0-1, so with these numbers hue weighs about 3.6 times stronger than saturation and brightness..
Update: The original solution I posted contained several errors:
color.GetBrightness()
method. This is, to put it mildly, totally useless. To wit:Blue
andYellow
have the same value of0.5
!I have replaced most of the original answer with corrected code:
These now are the new version of the methods, each returning the index of the closest match found:
A few helper functions:
Here is the handy little helper I used for the screenshot texts:
I have updated the screenshot to display not only 13 colors but also a number of mostly reddish colors for testing; all colors are shown with their values for hue, saturation and brightness. The last three numbers are the results of the three methods.
As you can see, the simple distance method is quite misleading hue-wise for bright and non-saturated colors: The last color (Ivory) is in fact a bright and pale yellow!
The third method which gauges all color properties is best imo. You should play around with the gauging numbers, though!
In the end it really depends on what you want to achieve; if, as it seems, you only care about the hues of the colors, simply go for the first method! You can call it, using your array like this:
For more on color distances see Wikipedia!