private static double ComputeH(RgbType rgb, double cmax, double delta) { double hue; if (delta == 0) { hue = 0; } else if (cmax == rgb.Red) { hue = ((rgb.Green - rgb.Blue) / delta) % 6; } else if (cmax == rgb.Green) { hue = ((rgb.Blue - rgb.Red) / delta) + 2; } else { hue = ((rgb.Red - rgb.Green) / delta) + 4; } hue = Math.Round(hue * 60); if (hue < 0) { hue += 360; } return(hue); }
private static RgbType HexToRgb(this string hexIn, double opacity) { string hex = hexIn.Trim(); var rgb = new RgbType(); var regex = new Regex("^#?(([0-9a-zA-Z]{3}){1,3})$"); Match match = regex.Match(hex); if (match != null) { rgb.Opacity = opacity; hex = match.Value.Trim('#'); if (hex.Length == 6) { rgb.Red = Convert.ToInt32(hex.Substring(0, 2), 16); rgb.Green = Convert.ToInt32(hex.Substring(2, 2), 16); rgb.Blue = Convert.ToInt32(hex.Substring(4, 2), 16); } else if (hex.Length == 3) { rgb.Red = Convert.ToInt32(hex.Substring(0, 1) + hex.Substring(0, 1), 16); rgb.Green = Convert.ToInt32(hex.Substring(1, 1) + hex.Substring(1, 1), 16); rgb.Blue = Convert.ToInt32(hex.Substring(2, 1) + hex.Substring(2, 1), 16); } } return(rgb); }
private static HslType HexToHsl(this string hexIn) { /* * the source text is taken from here (with minor modifications): * https://css-tricks.com/converting-color-spaces-in-javascript/ */ // Convert hex to RGB first. Ignore opacity RgbType rgb = hexIn.HexToRgb(1); // Then to HSL rgb.ToHsl(); var cmin = rgb.Min(); var cmax = rgb.Max(); var delta = cmax - cmin; var hls = new HslType { Hue = ComputeH(rgb, cmax, delta), Lightness = (cmax + cmin) / 2 }; hls.Saturation = delta == 0 ? 0 : delta / (1 - Math.Abs(2 * hls.Lightness - 1)); hls.Saturation = Convert.ToDouble(String.Format("{0:0.0}", hls.Saturation * 100)); hls.Lightness = Convert.ToDouble(String.Format("{0:0.0}", hls.Lightness * 100)); hls.Round(); return(hls); }