1
/////////////////////////////////////////////////////////////////////////////////
3
// Copyright (C) Rick Brewster, Tom Jackson, and past contributors. //
4
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
5
// See src/Resources/Files/License.txt for full licensing and attribution //
8
/////////////////////////////////////////////////////////////////////////////////
16
/// "A Primer on Building a Color Picker User Control with GDI+ in Visual Basic .NET or C#"
17
/// http://www.msdnaa.net/Resources/display.aspx?ResID=2460
19
public struct HsvColor
21
public int Hue; // 0-360
22
public int Saturation; // 0-100
23
public int Value; // 0-100
25
public static bool operator== (HsvColor lhs, HsvColor rhs)
27
if ((lhs.Hue == rhs.Hue) &&
28
(lhs.Saturation == rhs.Saturation) &&
29
(lhs.Value == rhs.Value))
39
public static bool operator!= (HsvColor lhs, HsvColor rhs)
44
public override bool Equals(object obj)
46
return this == (HsvColor)obj;
49
public override int GetHashCode()
51
return (Hue + (Saturation << 8) + (Value << 16)).GetHashCode();;
54
public HsvColor(int hue, int saturation, int value)
56
if (hue < 0 || hue > 360)
58
throw new ArgumentOutOfRangeException("hue", "must be in the range [0, 360]");
61
if (saturation < 0 || saturation > 100)
63
throw new ArgumentOutOfRangeException("saturation", "must be in the range [0, 100]");
66
if (value < 0 || value > 100)
68
throw new ArgumentOutOfRangeException("value", "must be in the range [0, 100]");
72
Saturation = saturation;
76
// public static HsvColor FromColor(Color color)
78
// RgbColor rgb = new RgbColor(color.R, color.G, color.B);
79
// return rgb.ToHsv();
82
// public Color ToColor()
84
// RgbColor rgb = ToRgb();
85
// return Color.FromArgb(rgb.Red, rgb.Green, rgb.Blue);
88
public RgbColor ToRgb()
90
// HsvColor contains values scaled as in the color wheel:
100
// Scale Hue to be between 0 and 360. Saturation
101
// and value scale to be between 0 and 1.
102
h = (double) Hue % 360;
103
s = (double) Saturation / 100;
104
v = (double) Value / 100;
108
// If s is 0, all colors are the same.
109
// This is some flavor of gray.
120
double fractionalSector;
124
// The color wheel consists of 6 sectors.
125
// Figure out which sector you're in.
127
sectorNumber = (int)(Math.Floor(sectorPos));
129
// get the fractional part of the sector.
130
// That is, how many degrees into the sector
132
fractionalSector = sectorPos - sectorNumber;
134
// Calculate values for the three axes
137
q = v * (1 - (s * fractionalSector));
138
t = v * (1 - (s * (1 - fractionalSector)));
140
// Assign the fractional colors to r, g, and b
141
// based on the sector the angle is in.
142
switch (sectorNumber)
181
// return an RgbColor structure, with values scaled
182
// to be between 0 and 255.
183
return new RgbColor((int)(r * 255), (int)(g * 255), (int)(b * 255));
186
public override string ToString()
188
return String.Format("({0}, {1}, {2})", Hue, Saturation, Value);