1using System.Drawing; 2 3namespace WindowCapture.Helpers 4{ 5 /// <summary> 6 /// Shared color utilities: brightness, tint conversion, adaptive text color. 7 /// </summary> 8 public static class ColorHelper 9 { 10 /// <summary> 11 /// Perceived brightness of a color (0.0 = black, 1.0 = white). 12 /// Uses ITU-R BT.601 luma weights: 0.299R + 0.587G + 0.114B. 13 /// </summary> 14 public static float GetBrightness(Color c) 15 { 16 return (c.R * 0.299f + c.G * 0.587f + c.B * 0.114f) / 255f; 17 } 18 19 /// <summary> 20 /// Convert ARGB color + alpha to AABBGGRR int for DWM SetWindowCompositionAttribute. 21 /// </summary> 22 public static int ToABGR(int alpha, Color c) 23 { 24 return (alpha << 24) | (c.B << 16) | (c.G << 8) | c.R; 25 } 26 27 /// <summary> 28 /// Return a light or dark text color depending on the tint brightness. 29 /// </summary> 30 public static Color GetAdaptiveTextColor(Color tint, int textAlpha = 220, float threshold = 0.45f) 31 { 32 float br = GetBrightness(tint); 33 return br < threshold 34 ? Color.FromArgb(textAlpha, 255, 255, 255) 35 : Color.FromArgb(textAlpha, 0, 0, 0); 36 } 37 38 /// <summary> 39 /// Return a copy of the color with a different alpha value (0-255). 40 /// </summary> 41 public static Color WithAlpha(Color c, int alpha) 42 { 43 return Color.FromArgb(alpha, c.R, c.G, c.B); 44 } 45 46 public static string ColorToHex(Color c) 47 { 48 return string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B); 49 } 50 51 public static string ColorToHexWeb(Color c) 52 { 53 if (c.A == 255) 54 return string.Format("#{0:X2}{1:X2}{2:X2}", c.R, c.G, c.B); 55 else 56 return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B); 57 } 58 } 59}