HSL Color to RGB - CSharp System.Drawing

CSharp examples for System.Drawing:Color RGB

Description

HSL Color to RGB

Demo Code


using Windows.UI;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from w  w  w.ja  v a  2  s .  co  m

public class Main{
        public static Color HSL2RGB(HSL hsl)
        {
            if (hsl.Saturation == 0)
            {
                return default(Color);
            }
            else
            {
                double h = hsl.Hue;
                double s = hsl.Saturation;
                double l = hsl.Lightness;

                h = Math.Max(0, Math.Min(360, h));
                s = Math.Max(0, Math.Min(1, s));
                l = Math.Max(0, Math.Min(1, l));
                {
                    double q = (l < 0.5) ? (l * (1.0 + s)) : (l + s - (l * s));
                    double p = (2.0 * l) - q;

                    double hk = h / 360.0;
                    double[] t = new double[3];
                    t[0] = hk + (1.0 / 3.0);
                    t[1] = hk;
                    t[2] = hk - (1.0 / 3.0);

                    for (int i = 0; i < 3; i++)
                    {
                        if (t[i] < 0)
                        {
                            t[i] += 1.0;
                        }

                        if (t[i] > 1)
                        {
                            t[i] -= 1.0;
                        }

                        if ((t[i] * 6) < 1)
                        {
                            t[i] = p + ((q - p) * 6.0 * t[i]);
                        }
                        else if ((t[i] * 2.0) < 1)
                        {
                            t[i] = q;
                        }
                        else if ((t[i] * 3.0) < 2)
                        {
                            t[i] = p + ((q - p) * ((2.0 / 3.0) - t[i]) * 6.0);
                        }
                        else
                        {
                            t[i] = p;
                        }
                    }

                    return Color.FromArgb(
                        0xFF,
                        (byte)Convert.ToInt32(double.Parse(string.Format("{0:0.00}", t[0] * 255.0))),
                        (byte)Convert.ToInt32(double.Parse(string.Format("{0:0.00}", t[1] * 255.0))),
                        (byte)Convert.ToInt32(double.Parse(string.Format("{0:0.00}", t[2] * 255.0))));
                }
            }
        }
}

Related Tutorials