Converts a colour from HSL to RGB - CSharp System.Drawing

CSharp examples for System.Drawing:Color Convert

Description

Converts a colour from HSL to RGB

Demo Code


using System.Drawing;
using System;//from  ww w.j  av  a2  s . c  om

public class Main{
        /// <summary> 
      /// Converts a colour from HSL to RGB 
      /// </summary> 
      /// <remarks>Adapted from the algoritm in Foley and Van-Dam</remarks> 
      /// <param name="hsl">The HSL value</param> 
      /// <returns>A Color structure containing the equivalent RGB values</returns> 
      public static Color HSL_to_RGB(HSL hsl) 
      { 
         int Max, Mid, Min;
         double q;

         Max = Round(hsl.L * 255);
         Min = Round((1.0 - hsl.S)*(hsl.L/1.0)*255);
         q   = (double)(Max - Min)/255;

         if ( hsl.H >= 0 && hsl.H <= (double)1/6 )
         {
            Mid = Round(((hsl.H - 0) * q) * 1530 + Min);
            return Color.FromArgb(Max,Mid,Min);
         }
         else if ( hsl.H <= (double)1/3 )
         {
            Mid = Round(-((hsl.H - (double)1/6) * q) * 1530 + Max);
            return Color.FromArgb(Mid,Max,Min);
         }
         else if ( hsl.H <= 0.5 )
         {
            Mid = Round(((hsl.H - (double)1/3) * q) * 1530 + Min);
            return Color.FromArgb(Min,Max,Mid);
         }
         else if ( hsl.H <= (double)2/3 )
         {
            Mid = Round(-((hsl.H - 0.5) * q) * 1530 + Max);
            return Color.FromArgb(Min,Mid,Max);
         }
         else if ( hsl.H <= (double)5/6 )
         {
            Mid = Round(((hsl.H - (double)2/3) * q) * 1530 + Min);
            return Color.FromArgb(Mid,Min,Max);
         }
         else if ( hsl.H <= 1.0 )
         {
            Mid = Round(-((hsl.H - (double)5/6) * q) * 1530 + Max);
            return Color.FromArgb(Max,Min,Mid);
         }
         else   return Color.FromArgb(0,0,0);
      }
        /// <summary>
      /// Custom rounding function.
      /// </summary>
      /// <param name="val">Value to round</param>
      /// <returns>Rounded value</returns>
      private static int Round(double val)
      {
         int ret_val = (int)val;
         
         int temp = (int)(val * 100);

         if ( (temp % 100) >= 50 )
            ret_val += 1;

         return ret_val;
      }
}

Related Tutorials