按标准公式计算。
// RGB转HSV
public static void RGB2HSV(int r, int g, int b, out float h, out float s, out float v)
{
float max = Math.Max(r, Math.Max(g,b));
float min = Math.Min(r, Math.Min(g,b));
// 计算hue
if(min == max) { h = 0;}
else if(max == r && g >= b)
{
h = 60*(g - b) / (max - min);
}
else if(max == r && g < b)
{
h = 360 + 60 * (g - b) / (max - min);
}
else if(max == g)
{
h = 120 + 60 * (b - r) / (max - min);
}
else
{
h = 240 + 60*(r - g) / (max - min);
}
// 计算saturation
if(max==0)
{
s = 0;
}
else
{
s = (max - min) / max;
}
// 计算v / brightness
v = max / 255;
}
// HSV转RGB
public static void HSV2RGB(float h, float s, float v, out int r, out int g, out int b)
{
// s,v为小数表示,如0.25表示25
float hi = (float)(Math.Floor(h/60))%6;
float f = h / 60 - hi;
float p = v * (1 - s);
float q = v * (1 - f * s);
float t = v * (1 - (1 - f) * s);
float r0=0, g0=0, b0=0;
switch ((int)hi)
{
case 0:
r0 = v; g0 = t; b0 = p;
break;
case 1:
r0 = q; g0 = v; b0 = p;
break;
case 2:
r0 = p; g0 = v; b0 = t;
break;
case 3:
r0 = p; g0 = q; b0 = v;
break;
case 4:
r0 = t; g0 = p; b0 = v;
break;
case 5:
r0 = v; g0 = p; b0 = q;
break;
}
// 四舍五入取整
r = (int)Math.Round(r0*255);
g = (int)Math.Round(g0*255);
b = (int)Math.Round(b0*255);
}