#962 – A Color Selection Box Organized by Hue, part I
December 2, 2013 2 Comments
Here’s some code that generates a spread of different colors. (We’ll later bind a ComboBox to the generated list of colors).
public class ColorWithInfo : IComparable { public Color Color { get; set; } public string Info { get { return string.Format("{0}/{1}/{2}", Color.R, Color.G, Color.B); } } public string HueSatBright { get { return string.Format("{0}/{1}/{2}", Hue, Saturation, Brightness); } } public float Hue { get { return System.Drawing.Color.FromArgb(Color.R, Color.G, Color.B).GetHue(); } } public float Saturation { get { return System.Drawing.Color.FromArgb(Color.R, Color.G, Color.B).GetSaturation(); } } public float Brightness { get { return System.Drawing.Color.FromArgb(Color.R, Color.G, Color.B).GetBrightness(); } } public int CompareTo(object obj) { ColorWithInfo cwiOther = obj as ColorWithInfo; // Sort by Hue, and then Saturation, and then Brightness if (this.Hue == cwiOther.Hue) { if (this.Saturation == cwiOther.Saturation) return this.Brightness.CompareTo(cwiOther.Brightness); else return this.Saturation.CompareTo(cwiOther.Saturation); } else return this.Hue.CompareTo(cwiOther.Hue); } } public static class ColorUtil { public static List<ColorWithInfo> GenerateColorList(int numValsPerColor) { List<ColorWithInfo> colorList = new List<ColorWithInfo>(); // Create increment such that we start at 0, end at 255, // and have a total of numValsPerColor within that range. int delta = Convert.ToInt32(255.0 / ((double)numValsPerColor - 1.0)); for (int r = 0; r < numValsPerColor; r++) for (int g = 0; g < numValsPerColor; g++) for (int b = 0; b < numValsPerColor; b++) { ColorWithInfo cwi = new ColorWithInfo { Color = Color.FromRgb((byte)(r * delta), (byte)(g * delta), (byte)(b * delta))}; colorList.Add(cwi); } colorList.Sort(); return colorList; } }