Converts an RGBA Color the HSL representation. - CSharp System.Drawing

CSharp examples for System.Drawing:Color Convert

Description

Converts an RGBA Color the HSL representation.

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using Windows.UI;
using System.Reflection;
using System;/*w  w w  .ja va  2 s  . c  o m*/

public class Main{
        /// <summary>
        /// Converts an RGBA Color the HSL representation.
        /// </summary>
        /// <param name="color">The Color to convert.</param>
        /// <returns>HslColor.</returns>
        public static HslColor ToHsl(this Color color)
        {
            const double toDouble = 1.0 / 255;
            var r = toDouble * color.R;
            var g = toDouble * color.G;
            var b = toDouble * color.B;
            var max = Math.Max(Math.Max(r, g), b);
            var min = Math.Min(Math.Min(r, g), b);
            var chroma = max - min;
            double h1;

            if (chroma == 0)
            {
                h1 = 0;
            }
            else if (max == r)
            {
                // The % operator doesn't do proper modulo on negative
                // numbers, so we'll add 6 before using it
                h1 = (((g - b) / chroma) + 6) % 6;
            }
            else if (max == g)
            {
                h1 = 2 + ((b - r) / chroma);
            }
            else
            {
                h1 = 4 + ((r - g) / chroma);
            }

            double lightness = 0.5 * (max + min);
            double saturation = chroma == 0 ? 0 : chroma / (1 - Math.Abs((2 * lightness) - 1));
            HslColor ret;
            ret.H = 60 * h1;
            ret.S = saturation;
            ret.L = lightness;
            ret.A = toDouble * color.A;
            return ret;
        }
}

Related Tutorials