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

CSharp examples for System.Drawing:Color Convert

Description

Converts an RGBA Color the HSV representation.

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using Windows.UI;
using System.Reflection;
using System;/*from  ww w  .  j a va 2  s.com*/

public class Main{
        /// <summary>
        /// Converts an RGBA Color the HSV representation.
        /// </summary>
        /// <param name="color">Color to convert.</param>
        /// <returns>HsvColor</returns>
        public static HsvColor ToHsv(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 saturation = chroma == 0 ? 0 : chroma / max;
            HsvColor ret;
            ret.H = 60 * h1;
            ret.S = saturation;
            ret.V = max;
            ret.A = toDouble * color.A;
            return ret;
        }
}

Related Tutorials