Sort System.Media.Colors according to position in visible spectrum

You want to sort colors by hue, it seems. To do that, you need to compute the hue of a color, and the Wpf System.Media.Color struct doesn't include properties to do that for you.

You've two options:

  • You can manually compute the hue. This isn't really hard, but it's messy: lots of if-then statements. Sample code doing this can be found on devx. This is more work and less readable, but probably the faster option.
  • You can use System.Drawing.Color.GetHue. The older winforms-era System.Drawing color structure does support computing the hue. That makes the code really simple; something like System.Drawing.Color.FromArgb(col.R, col.G, col.B).GetHue() will suffice - nice and short! However, it does mean you'll be dealing with two structs with identical names and you'll of course need ro reference the System.Drawing.dll assembly. These kind of methods tend to be slow and do lots of sanity checking, so if performance is critical this is likely to be less attractive.

The colorspace is three-dimensional. Though you can sort along one direction (such as the hue, here), the resulting sequence of colors will only appear continuous if you keep the other two directions (saturation and brightness in the HSB model) constant. That's why most color-pickers choose a two-dimensional representation, but even then, you must leave one dimension constant within a given color picker to maintain a continuous gradient.