You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
98 lines
2.6 KiB
98 lines
2.6 KiB
using System; |
|
using System.Numerics; |
|
|
|
public static class ColorConvertExtension |
|
{ |
|
/// <summary> |
|
/// 将RGB颜色转换为HSV颜色空间 |
|
/// </summary> |
|
/// <param name="rgb">RGB颜色向量,X=R, Y=G, Z=B,取值范围0-1</param> |
|
/// <returns>HSV颜色向量,X=H(0-360), Y=S(0-1), Z=V(0-1)</returns> |
|
public static Vector3 RGBToHSV(this Vector3 rgb) |
|
{ |
|
float r = rgb.X; |
|
float g = rgb.Y; |
|
float b = rgb.Z; |
|
|
|
float max = Math.Max(r, Math.Max(g, b)); |
|
float min = Math.Min(r, Math.Min(g, b)); |
|
float delta = max - min; |
|
|
|
float h = 0f; |
|
float s = 0f; |
|
float v = max; |
|
|
|
// 计算色相 (H) |
|
if (delta > 0f) |
|
{ |
|
if (max == r) |
|
{ |
|
h = (g - b) / delta; |
|
if (h < 0f) h += 6f; |
|
} |
|
else if (max == g) |
|
{ |
|
h = 2f + (b - r) / delta; |
|
} |
|
else // max == b |
|
{ |
|
h = 4f + (r - g) / delta; |
|
} |
|
|
|
h *= 60f; // 转换为度数 |
|
} |
|
|
|
// 计算饱和度 (S) |
|
if (max > 0f) |
|
{ |
|
s = delta / max; |
|
} |
|
|
|
return new Vector3(h, s, v); |
|
} |
|
|
|
/// <summary> |
|
/// 将HSV颜色转换为RGB颜色空间 |
|
/// </summary> |
|
/// <param name="hsv">HSV颜色向量,X=H(0-360), Y=S(0-1), Z=V(0-1)</param> |
|
/// <returns>RGB颜色向量,X=R, Y=G, Z=B,取值范围0-1</returns> |
|
public static Vector3 HSVToRGB(this Vector3 hsv) |
|
{ |
|
float h = hsv.X; |
|
float s = hsv.Y; |
|
float v = hsv.Z; |
|
|
|
// 处理色相超出范围的情况 |
|
h = h % 360f; |
|
if (h < 0f) h += 360f; |
|
|
|
// 限制饱和度和明度在0-1范围内 |
|
s = Math.Clamp(s, 0f, 1f); |
|
v = Math.Clamp(v, 0f, 1f); |
|
|
|
// 如果饱和度为0,直接返回灰度值 |
|
if (s <= 0f) |
|
{ |
|
return new Vector3(v, v, v); |
|
} |
|
|
|
// 将色相转换为0-6的范围 |
|
float hNormalized = h / 60f; |
|
int sector = (int)hNormalized; |
|
float fractional = hNormalized - sector; |
|
|
|
float p = v * (1f - s); |
|
float q = v * (1f - s * fractional); |
|
float t = v * (1f - s * (1f - fractional)); |
|
|
|
return sector switch |
|
{ |
|
0 => new Vector3(v, t, p), |
|
1 => new Vector3(q, v, p), |
|
2 => new Vector3(p, v, t), |
|
3 => new Vector3(p, q, v), |
|
4 => new Vector3(t, p, v), |
|
_ => new Vector3(v, p, q) // 5 或 其他情况 |
|
}; |
|
} |
|
} |