get rgb from hsv in csharp

Here's a code snippet that converts HSV to RGB in C#:

main.cs
public static void HsvToRgb(double h, double s, double v, out byte r, out byte g, out byte b)
{
    var hi = (int)Math.Floor(h / 60.0) % 6;
    var f = (h / 60.0) - Math.Floor(h / 60.0);
    var p = v * (1.0 - s);
    var q = v * (1.0 - (f * s));
    var t = v * (1.0 - ((1.0 - f) * s));

    switch (hi)
    {
        case 0:
            r = (byte)Math.Round(v * 255);
            g = (byte)Math.Round(t * 255);
            b = (byte)Math.Round(p * 255);
            break;
        case 1:
            r = (byte)Math.Round(q * 255);
            g = (byte)Math.Round(v * 255);
            b = (byte)Math.Round(p * 255);
            break;
        case 2:
            r = (byte)Math.Round(p * 255);
            g = (byte)Math.Round(v * 255);
            b = (byte)Math.Round(t * 255);
            break;

        case 3:
            r = (byte)Math.Round(p * 255);
            g = (byte)Math.Round(q * 255);
            b = (byte)Math.Round(v * 255);
            break;
        case 4:
            r = (byte)Math.Round(t * 255);
            g = (byte)Math.Round(p * 255);
            b = (byte)Math.Round(v * 255);
            break;
        default:
            r = (byte)Math.Round(v * 255);
            g = (byte)Math.Round(p * 255);
            b = (byte)Math.Round(q * 255);
            break;
    }
}
1305 chars
44 lines

Here's how you can use the function:

main.cs
double h = 180.0; // hue value
double s = 0.5;   // saturation value
double v = 0.5;   // value value
byte r, g, b;

HsvToRgb(h, s, v, out r, out g, out b);

Console.WriteLine($"RGB value: ({r}, {g}, {b})")
207 chars
9 lines

gistlibby LogSnag