using System;
using System.Drawing;
/// <summary>
/// freeware helper class for converting color schemes
/// (W) 2011 by admin of codezentrale.6x.to
/// </summary>
public static class ColorConvert
{
public struct HSV
{
/// <summary>
/// Hue, Farbton [0.0° .. 360.0°]
/// </summary>
public double hue;
/// <summary>
/// Saturation, Sättigung [0.0 .. 1.0]
/// </summary>
public double saturation;
/// <summary>
/// Value, Helligkeit [0.0 .. 1.0]
/// </summary>
public double value;
public HSV(double h, double s, double v)
{
hue = h;
saturation = s;
value = v;
}
}
public struct RGB
{
/// <summary>
/// red, Rot [0 .. 255]
/// </summary>
public int red;
/// <summary>
/// green, Grün [0 .. 255]
/// </summary>
public int green;
/// <summary>
/// blue, Blau [0 .. 255]
/// </summary>
public int blue;
public RGB(int r, int g, int b)
{
red = r;
green = g;
blue = b;
}
}
/// <summary>
/// converts Color to HSV
/// </summary>
/// <param name="c">Color</param>
/// <returns>HSV struct</returns>
public static HSV ColorToHSV(Color c)
{
int max = Math.Max(c.R, Math.Max(c.G, c.B));
int min = Math.Min(c.R, Math.Min(c.G, c.B));
double h = c.GetHue();
double s = (max == 0) ? 0.0 : 1.0 - (1.0 * (double)min / (double)max);
double v = (double)max / 255.0;
return new HSV(h, s, v);
}
/// <summary>
/// converts HSV to Color
/// </summary>
/// <param name="hsv">HSV struct to convert</param>
/// <returns>Color</returns>
public static Color HSVToColor(HSV hsv)
{
Color c = Color.Black;
int hi = (int)(Math.Floor(hsv.hue / 60.0)) % 6;
double f = hsv.hue / 60.0 - Math.Floor(hsv.hue / 60.0);
hsv.value = hsv.value * 255.0;
int v = (int)hsv.value;
int p = (int)(hsv.value * (1.0 - hsv.saturation));
int q = (int)(hsv.value * (1.0 - f * hsv.saturation));
int t = (int)(hsv.value * (1.0 - (1.0 - f) * hsv.saturation));
switch (hi)
{
case 0: c = Color.FromArgb(255, v, t, p); break;
case 1: c = Color.FromArgb(255, q, v, p); break;
case 2: c = Color.FromArgb(255, p, v, t); break;
case 3: c = Color.FromArgb(255, p, q, v); break;
case 4: c = Color.FromArgb(255, t, p, v); break;
default: c = Color.FromArgb(255, v, p, q); break;
}
return c;
}
/// <summary>
/// converts Color to RGB
/// </summary>
/// <param name="c">Color</param>
/// <returns>RGB struct</returns>
public static RGB ColorToRGB(Color c)
{
return new RGB(c.R, c.G, c.B);
}
/// <summary>
/// converts RGB to Color
/// </summary>
/// <param name="rgb">RGB struct</param>
/// <returns>Color</returns>
public static Color RGBToColor(RGB rgb)
{
return Color.FromArgb(rgb.red, rgb.green, rgb.blue);
}
}