using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RichCreator.Utility { public class ColorUtils { /// /// RGB转换为HSV颜色空间 /// /// Range(0-255) /// Range(0-255) /// Range(0-255) /// Range(0-1.0) /// Range(0-1.0) /// Range(0-1.0) public static void RGBtoHSV(byte r, byte g, byte b, out float h, out float s, out float v) { float min, max, delta; min = Math.Min(r, Math.Min(g, b)); max = Math.Max(r, Math.Max(g, b)); v = max; // v delta = max - min; if (max != 0) { s = delta / max; // s } else { // r = g = b = 0 // s = 0, v is undefined s = 0; h = 0; return; } if (r == max) { h = delta == 0 ? 0 : (g - b) / delta;// between yellow & magenta } else if (g == max) { h = 2 + (b - r) / delta; // between cyan & yellow } else { h = 4 + (r - g) / delta; // between magenta & cyan } h *= 60; // degrees if (h < 0) { h += 360; } h = h / 360; v = v / 255; } /// /// HSV转换为RGB颜色空间 /// /// Range(0.0~1.0) /// Range(0.0~1.0) /// Range(0.0~1.0) /// Range(0~255) /// Range(0~255) /// Range(0~255) public static void HSVtoRGB(float h, float s, float v, out byte r, out byte g, out byte b) { h = h * 360; v = v * 255; int i; float f, p, q, t; if (s == 0) { // achromatic (grey) r = g = b = (byte)Math.Round(v); return; } h /= 60; // sector 0 to 5 i = (Int32)Math.Floor(h); f = h - i; // factorial part of h p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch (i) { case 0: r = (byte)Math.Round(v); g = (byte)Math.Round(t); b = (byte)Math.Round(p); break; case 1: r = (byte)Math.Round(q); g = (byte)Math.Round(v); b = (byte)Math.Round(p); break; case 2: r = (byte)Math.Round(p); g = (byte)Math.Round(v); b = (byte)Math.Round(t); break; case 3: r = (byte)Math.Round(p); g = (byte)Math.Round(q); b = (byte)Math.Round(v); break; case 4: r = (byte)Math.Round(t); g = (byte)Math.Round(p); b = (byte)Math.Round(v); break; default: // case 5: r = (byte)Math.Round(v); g = (byte)Math.Round(p); b = (byte)Math.Round(q); break; } } } }