颜色转换:HSB颜色 与 RGB颜色
颜色转换:HSB颜色 与 RGB颜色
/// <summary> /// HSB转RGB /// </summary> /// <param name="hue">色调,°,0~360</param> /// <param name="saturation">饱和度,%, 0~100</param> /// <param name="brightness">亮度,%, 0~100</param> /// <returns>返回:Color</returns> public Color HSB2RGB(float hue, int saturation, int brightness) { double r = 0; double g = 0; double b = 0; hue = hue % 360; float sat = saturation / 100.0f; float bri = brightness / 100.0f; if (sat == 0) { r = g = b = bri; } else { // the color wheel consists of 6 sectors. Figure out which sector you're in. double sectorPos = hue / 60.0; int sectorNumber = (int)(Math.Floor(sectorPos)); // get the fractional part of the sector double fractionalSector = sectorPos - sectorNumber; // calculate values for the three axes of the color. double p = bri * (1.0 - sat); double q = bri * (1.0 - (sat * fractionalSector)); double t = bri * (1.0 - (sat * (1 - fractionalSector))); // assign the fractional colors to r, g, and b based on the sector the angle is in. switch (sectorNumber) { case 0: r = bri; g = t; b = p; break; case 1: r = q; g = bri; b = p; break; case 2: r = p; g = bri; b = t; break; case 3: r = p; g = q; b = bri; break; case 4: r = t; g = p; b = bri; break; case 5: r = bri; g = p; b = q; break; } } int red = Convert.ToInt32(r * 255); int green = Convert.ToInt32(g * 255); int blue = Convert.ToInt32(b * 255); ; return Color.FromArgb(Convert.ToByte(255), red, green, blue); }
/// <summary> /// RGB转HSB /// </summary> /// <param name="red"></param> /// <param name="green"></param> /// <param name="blue"></param> /// <param name="hue"></param> /// <param name="sat"></param> /// <param name="bri"></param> public void RGB2HSB(int red, int green, int blue, out double hue, out double sat, out double bri) { double r = ((double)red / 255.0); double g = ((double)green / 255.0); double b = ((double)blue / 255.0); double max = Math.Max(r, Math.Max(g, b)); double min = Math.Min(r, Math.Min(g, b)); hue = 0.0; if (max == r && g >= b) { if (max - min == 0) hue = 0.0; else hue = 60 * (g - b) / (max - min); } else if (max == r && g < b) { hue = 60 * (g - b) / (max - min) + 360; } else if (max == g) { hue = 60 * (b - r) / (max - min) + 120; } else if (max == b) { hue = 60 * (r - g) / (max - min) + 240; } sat = (max == 0) ? 0.0 : (1.0 - ((double)min / (double)max)); bri = max; }