Friday, April 23, 2010

My HSL colour class

Want a unique set of colours without having to do any work? You need HSL.

Use:


for (var i = 0; i < 10; i++)
(Color)new ColorHsl((byte)((float)i / 10 * 255), 127, 127)


Class (Note, I mostly ripped this off from elsewhere, but mine 1) actually works, 2) is easy to use.):


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace UserInterface
{
public class ColorHsl
{
public ColorHsl(byte h, byte s, byte l)
{
H = h;
S = s;
L = l;
}

public byte H, S, L;

public static implicit operator Color(ColorHsl colorHsl)
{
double r, g, b, h, s, l; //this function works with floats between 0 and 1
double temp1, temp2, tempr, tempg, tempb;
h = colorHsl.H / 256.0;
s = colorHsl.S / 256.0;
l = colorHsl.L / 256.0;

//If saturation is 0, the color is a shade of gray
if (s == 0)
{
r = g = b = l;
}
else
{
//Set the temporary values
if (l < 0.5)
{
temp2 = l * (1 + s);
}
else
{
temp2 = (l + s) - (l * s);
}

temp1 = 2 * l - temp2;
tempr = h + 1.0 / 3.0;

if (tempr > 1)
{
tempr--;
}

tempg = h;
tempb = h - 1.0 / 3.0;
if (tempb < 0)
tempb++;

//Red
if (tempr < 1.0 / 6.0) r = temp1 + (temp2 - temp1) * 6.0 * tempr;
else if (tempr < 0.5) r = temp2;
else if (tempr < 2.0 / 3.0) r = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempr) * 6.0;
else r = temp1;

//Green
if (tempg < 1.0 / 6.0) g = temp1 + (temp2 - temp1) * 6.0 * tempg;
else if (tempg < 0.5) g = temp2;
else if (tempg < 2.0 / 3.0) g = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempg) * 6.0;
else g = temp1;

//Blue
if (tempb < 1.0 / 6.0) b = temp1 + (temp2 - temp1) * 6.0 * tempb;
else if (tempb < 0.5) b = temp2;
else if (tempb < 2.0 / 3.0) b = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempb) * 6.0;
else b = temp1;
}

return Color.FromRgb(Convert.ToByte(r * 255), Convert.ToByte(g * 255), Convert.ToByte(b * 255));
}
}
}

No comments:

Post a Comment