Color extension methods:
public static Color Blend(this Color thisColor, Color blendToColor, double blendToPercent)
{
blendToPercent = (1-blendToPercent).ForceBounds(0, 1);
byte r = (byte)((thisColor.R * blendToPercent) + blendToColor.R * (1 - blendToPercent));
byte g = (byte)((thisColor.G * blendToPercent) + blendToColor.G * (1 - blendToPercent));
byte b = (byte)((thisColor.B * blendToPercent) + blendToColor.B * (1 - blendToPercent));
return Color.FromArgb(r, g, b);
}
public static Color MakeDarker(this Color thisColor, double darknessPercent)
{
darknessPercent = darknessPercent.ForceBounds(0, 1);
return Blend(thisColor, Color.Black, darknessPercent);
}
public static Color MakeLighter(this Color thisColor, double lightnessPercent)
{
lightnessPercent = lightnessPercent.ForceBounds(0, 1);
return Blend(thisColor, Color.White, lightnessPercent);
}
public static Color MakeTransparent(this Color thisColor, double transparentPercent)
{
transparentPercent = 255 - (transparentPercent.ForceBounds(0, 1) * 255);
return Color.FromArgb(thisColor.ToArgb() + ((int)transparentPercent * 0x1000000));
}
/// <summary>
/// Returns a contrasting ForeColor for the specified BackColor. If the source BackColor is dark,
/// then the lightForeColor is returned. If the BackColor is light, then the darkForeColor is returned.
/// </summary>
public static Color DetermineForecolor(this Color thisColor, Color lightForeColor, Color darkForeColor)
{
// Counting the perceptive luminance - human eye favors green color...
double a = 1 - (0.299 * thisColor.R + 0.587 * thisColor.G + 0.114 * thisColor.B) / 255;
return a < 0.5 ? darkForeColor : lightForeColor;
}
/// <summary>
/// Returns a contrasting ForeColor for the specified BackColor. If the source BackColor is dark,
/// then the White is returned. If the BackColor is light, then the Black is returned.
/// </summary>
public static Color DetermineForecolor(this Color thisColor)
{
return DetermineForecolor(thisColor, Color.White, Color.Black);
}
public static int ToRGB(this Color thisColor)
{
return (thisColor.ToArgb() & 0xFFFFFF);
}
public static int ToBGR(this Color thisColor)
{
return (thisColor.B << 16) | (thisColor.G << 8) | (thisColor.R << 0);
}
public static double ForceBounds(this double thisDouble, double minLimit, double maxLimit)
{
return Math.Max(Math.Min(thisDouble, maxLimit), minLimit);
}
This has been really helpful for creating GUIs with lots of color shades and highlights:
var PenColor = Color.DarkOrange.MakeDarker(0.25d); // 25% Darker. 100% darker would be black.
var PenColor = Color.Blue.MakeLighter(0.15d); // 15% Lighter. 100% lighter would be white.
var PenColor = Color.Red.MakeTransparent(0.6d); // 60% Transparent. 100% Transparent would be invisible.
var PenColor = Color.Red.Blend(Color.Blue, 0.2d); // Blend Red and Blue 20%. 100% would be blue.