Sunday, September 23, 2012

Make Color Lighter or Darker in C#

While developing the user interface of an application you may need to change the color of a specific element to draw user's attention. The most common technique to do so is to make the element's background or foreground color lighter or darker. The method I use simply applies a given correcttion factor in the interval [-1, 1] to the red, green and blue color components. Negative values produce darker colors and positive ones produce lighter colors.

Here's the C# source code of the color lightening/darkening method:

/// <summary>
/// Creates color with corrected brightness.
/// </summary>
/// <param name="color">Color to correct.</param>
/// <param name="correctionFactor">The brightness correction factor. Must be between -1 and 1. 
/// Negative values produce darker colors.</param>
/// <returns>
/// Corrected <see cref="Color"/> structure.
/// </returns>
public static Color ChangeColorBrightness(Color color, float correctionFactor)
{
    float red = (float)color.R;
    float green = (float)color.G;
    float blue = (float)color.B;

    if (correctionFactor < 0)
    {
        correctionFactor = 1 + correctionFactor;
        red *= correctionFactor;
        green *= correctionFactor;
        blue *= correctionFactor;
    }
    else
    {
        red = (255 - red) * correctionFactor + red;
        green = (255 - green) * correctionFactor + green;
        blue = (255 - blue) * correctionFactor + blue;
    }

    return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
}

See also:

5 comments:

  1. Works like a charm, thanks!

    PS: in SL5 I needed to change the conversion in the last line to (byte) instead of (int).

    ReplyDelete
  2. Thank you. It turned out to be a bit trickier than I could expect at first glance.

    ReplyDelete
  3. More than 6 years and it is still helping. Thanks for saving my day!

    ReplyDelete