How to make specific color darken or lighten based on value in wpf?

Shailesh Jaiswal picture Shailesh Jaiswal · Oct 15, 2012 · Viewed 17.4k times · Source

I am developing wpf application. I am having the instance of Color object in C#. Suppose I have instance of red Color object i.e. Color c = Color.FromArgb(255,255,0,0) Now suppose that I have one value which ranges from 1 to 10. So based on this value I want to change the color of the 'c' object. I want light red for 1 and dark red for 10. The light red becomes the dark as the value increases from 1. How can I do this in C# for wpf application ? Can you please provide me any code or link through which I can resolve the above issue ?

Answer

Nikolay Khil picture Nikolay Khil · Oct 15, 2012

You can try to simply multiply red, green and blue components by some coefficient.

public static Color ChangeLightness(this Color color, float coef)
{
    return Color.FromArgb((int)(color.R * coef), (int)(color.G * coef),
        (int)(color.B * coef));
}

Or, if you'd like to use an integer value from 1 to 10 instead of the coefficient:

private const int MinLightness = 1;
private const int MaxLightness = 10;
private const float MinLightnessCoef = 1f;
private const float MaxLightnessCoef = 0.4f;

public static Color ChangeLightness(this Color color, int lightness)
{
    if (lightness < MinLightness)
        lightness = MinLightness;
    else if (lightness > MaxLightness)
        lightness = MaxLightness;

    float coef = MinLightnessCoef +
      (
        (lightness - MinLightness) *
          ((MaxLightnessCoef - MinLightnessCoef) / (MaxLightness - MinLightness))
      );

    return Color.FromArgb(color.A, (int)(color.R * coef), (int)(color.G * coef),
        (int)(color.B * coef));
}