Sets the absolute brightness of a color - CSharp System.Drawing

CSharp examples for System.Drawing:Color Brightness

Description

Sets the absolute brightness of a color

Demo Code


using System.Windows.Media;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from   w w w.j  a  va2 s.  com*/

public class Main{
        /// <summary>
      /// Sets the absolute brightness of a colour
      /// </summary>
      /// <param name="brightness">The luminance level to impose</param>
      /// <returns>an adjusted colour</returns>
      public static Color SetBrightness(this Color c, double brightness)
      {
         HSL hsl = c.ToHsl();
         hsl.L = brightness;
         return hsl.ToColor();
      }
        /// <summary>
      /// Converts a colour from HSL to RGB
      /// </summary>
      /// <remarks>Adapted from the algoritm in Foley and Van-Dam</remarks>
      /// <returns>A Color structure containing the equivalent RGB values</returns>
      public static Color ToColor(this HSL hsl)
      {
         double r = 0, g = 0, b = 0;
         double temp1, temp2;

         if (hsl.L == 0) {
            r = g = b = 0;
         } else {
            if (hsl.S == 0) {
               r = g = b = hsl.L;
            } else {
               temp2 = ((hsl.L <= 0.5) ? hsl.L * (1.0 + hsl.S) : hsl.L + hsl.S - (hsl.L * hsl.S));
               temp1 = 2.0 * hsl.L - temp2;

               double[] t3 = new double[] { hsl.H + 1.0 / 3.0, hsl.H, hsl.H - 1.0 / 3.0 };
               double[] clr = new double[] { 0, 0, 0 };
               for (int i = 0; i < 3; i++) {
                  if (t3[i] < 0)
                     t3[i] += 1.0;
                  if (t3[i] > 1)
                     t3[i] -= 1.0;

                  if (6.0 * t3[i] < 1.0)
                     clr[i] = temp1 + (temp2 - temp1) * t3[i] * 6.0;
                  else if (2.0 * t3[i] < 1.0)
                     clr[i] = temp2;
                  else if (3.0 * t3[i] < 2.0)
                     clr[i] = (temp1 + (temp2 - temp1) * ((2.0 / 3.0) - t3[i]) * 6.0);
                  else
                     clr[i] = temp1;
               }
               r = clr[0];
               g = clr[1];
               b = clr[2];
            }
         }

         return Color.FromRgb((byte)(255 * r), (byte)(255 * g), (byte)(255 * b));

      }
        //
      /// <summary>
      /// Converts RGB to HSL
      /// </summary>
      /// <returns>An HSL value</returns>
      public static HSL ToHsl(this Color c)
      {
         HSL hsl = new HSL();

         hsl.H = c.GetHue() / 360.0; // we store hue as 0-1 as opposed to 0-360
         hsl.L = c.GetBrightness();
         hsl.S = c.GetSaturation();

         return hsl;
      }
}

Related Tutorials