Skip to content

Instantly share code, notes, and snippets.

@bradmartin333
Created April 9, 2021 17:05
Show Gist options
  • Save bradmartin333/3a8b3ba678b7272026acde4d87559c67 to your computer and use it in GitHub Desktop.
Save bradmartin333/3a8b3ba678b7272026acde4d87559c67 to your computer and use it in GitHub Desktop.
Adaptation of geekymonkey's color RGB to HSL
using System;
using System.Drawing;
namespace Test
{
static class Colorizer
{
private static double _RainbowIDX;
public static Color GetNextRainbowColor()
{
ColorRGB c = HSL2RGB(_RainbowIDX, 0.5, 0.5);
_RainbowIDX += 0.04;
return Color.FromArgb(100, c.R, c.G, c.B);
}
public static Color GetScoreColor(double score)
{
ColorRGB c = HSL2RGB(1 / score, 0.5, 0.5);
return Color.FromArgb(100, c.R, c.G, c.B);
}
public struct ColorRGB
{
public byte R;
public byte G;
public byte B;
public ColorRGB(Color value)
{
this.R = value.R;
this.G = value.G;
this.B = value.B;
}
public static implicit operator Color(ColorRGB rgb)
{
Color c = Color.FromArgb(rgb.R, rgb.G, rgb.B);
return c;
}
public static explicit operator ColorRGB(Color c)
{
return new ColorRGB(c);
}
}
// Given H,S,L in range of 0-1
// Returns a Color (RGB struct) in range of 0-255
public static ColorRGB HSL2RGB(double h, double sl, double l)
{
double v;
double r, g, b;
r = l; // default to gray
g = l;
b = l;
v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
if (v > 0)
{
double m;
double sv;
int sextant;
double fract, vsf, mid1, mid2;
m = l + l - v;
sv = (v - m) / v;
h *= 6.0;
sextant = (int)h;
fract = h - sextant;
vsf = v * sv * fract;
mid1 = m + vsf;
mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
ColorRGB rgb;
rgb.R = Convert.ToByte(r * 255.0f);
rgb.G = Convert.ToByte(g * 255.0f);
rgb.B = Convert.ToByte(b * 255.0f);
return rgb;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment