C# has a very convenient getHue method, but I can't find a setHue method. Is there one?
If not, I think the best way to define a color after changing the hue would be to convert the HSL value to RGB, and then set the RGB value. I know there are formulas on the internet for doing this, but how would I best go about performing this conversion from HSL to RGB using C#?
Thank You
System.Drawing.Color
is a value type, which are almost always made immutable, especially in frameworks. That's why you can't setHue
on it, you can only construct a new value type with fields you need.
So, if you have a function that will give you RGB values for your HSB values, you can do it like this
Color oldColor = ...;
int red, green, blue;
FromHSB(oldColor.GetHue(), oldColor.GetSaturation(), oldColor.GetBrightness(), out red, out green out blue);
Color newColor = Color.FromArgb(oldColor.A, red, green, blue);
where FromHSB
looks like this
void FromHSB(float hue, float saturation, float brightness, out int red, out int green, out int blue)
{
// ...
}
To set the Hue you create a new Color
, maybe from a given one by using GetHue
and GetSaturation
. See below for the getBrightness
function!
I'm using this:
Color SetHue(Color oldColor)
{
var temp = new HSV();
temp.h = oldColor.GetHue();
temp.s = oldColor.GetSaturation();
temp.v = getBrightness(oldColor);
return ColorFromHSL(temp);
}
// A common triple float struct for both HSL & HSV
// Actually this should be immutable and have a nice constructor!!
public struct HSV { public float h; public float s; public float v;}
// the Color Converter
static public Color ColorFromHSL(HSV hsl)
{
if (hsl.s == 0)
{ int L = (int)hsl.v; return Color.FromArgb(255, L, L, L); }
double min, max, h;
h = hsl.h / 360d;
max = hsl.v < 0.5d ? hsl.v * (1 + hsl.s) : (hsl.v + hsl.s) - (hsl.v * hsl.s);
min = (hsl.v * 2d) - max;
Color c = Color.FromArgb(255, (int)(255 * RGBChannelFromHue(min, max,h + 1 / 3d)),
(int)(255 * RGBChannelFromHue(min, max,h)),
(int)(255 * RGBChannelFromHue(min, max,h - 1 / 3d)));
return c;
}
static double RGBChannelFromHue(double m1, double m2, double h)
{
h = (h + 1d) % 1d;
if (h < 0) h += 1;
if (h * 6 < 1) return m1 + (m2 - m1) * 6 * h;
else if (h * 2 < 1) return m2;
else if (h * 3 < 2) return m1 + (m2 - m1) * 6 * (2d / 3d - h);
else return m1;
}
Do not use the built-in GetBrightness
method! It returns the same value (0.5f) for red, magenta, cyan, blue and yellow (!). This is better:
// color brightness as perceived:
float getBrightness(Color c)
{ return (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f; }