I did a search for an HsbToRgb converter in the docs but didn't find anything containing "hsb" or "hsl", so I'm guessing it just doesn't exist. Just to make sure, though, are there any classes that support this conversion?
Update
I ended up going with this, which is slightly different than 0xA3's. I also added an AhsbToArgb
so I can convert to RGB and set the alpha channel in one shot.
AhsbToArgb
- allows for alpha channel:
public static Color AhsbToArgb(byte a, double h, double s, double b)
{
var color = HsbToRgb(h, s, b);
return Color.FromArgb(a, color.R, color.G, color.B);
}
HsbToRgb
- converts hue-saturation-brightness to red-green-blue:
public static Color HsbToRgb(double h, double s, double b)
{
if (s == 0)
return RawRgbToRgb(b, b, b);
else
{
var sector = h / 60;
var sectorNumber = (int)Math.Truncate(sector);
var sectorFraction = sector - sectorNumber;
var b1 = b * (1 - s);
var b2 = b * (1 - s * sectorFraction);
var b3 = b * (1 - s * (1 - sectorFraction));
switch (sectorNumber)
{
case 0:
return RawRgbToRgb(b, b3, b1);
case 1:
return RawRgbToRgb(b2, b, b1);
case 2:
return RawRgbToRgb(b1, b, b3);
case 3:
return RawRgbToRgb(b1, b2, b);
case 4:
return RawRgbToRgb(b3, b1, b);
case 5:
return RawRgbToRgb(b, b1, b2);
default:
throw new ArgumentException("Hue must be between 0 and 360");
}
}
}
RawRgbToRgb
- converts doubles to ints and returns a color object:
private static Color RawRgbToRgb(double rawR, double rawG, double rawB)
{
return Color.FromArgb(
(int)Math.Round(rawR * 255),
(int)Math.Round(rawG * 255),
(int)Math.Round(rawB * 255));
}