tags:

views:

1241

answers:

4

I would like to darken an existing color for use in a gradient brush. Could somebody tell me how to do this please?

C#, .net 2.0, GDI+

  Color AdjustBrightness(Color c1, float factor)
    {

        float r = ((c1.R * factor) > 255) ? 255 : (c1.R * factor);
        float g = ((c1.G * factor) > 255) ? 255 : (c1.G * factor);
        float b = ((c1.B * factor) > 255) ? 255 : (c1.B * factor);

        Color c  = Color.FromArgb(c1.A,(int)r, (int)g, (int)b);
        return c ;

    }
+8  A: 

Convert from RGB to HSV (or HSL), then adjust the V (or L) down and then convert back.

While System.Drawing.Colour provides methods to get hue (H), saturation (S) and brightness it does not provide much in the way of other conversions, notable nothing to create a new instance from HSV (or HSV values), but the conversion is pretty simple to implement. The wikipedia articles give decent converage, starting here: "HSL and HSV".

Richard
+3  A: 

As a simple approach, you can just factor the RGB values:

    Color c1 = Color.Red;
    Color c2 = Color.FromArgb(c1.A,
        (int)(c1.R * 0.8), (int)(c1.G * 0.8), (int)(c1.B * 0.8));

(which should darken it; or, for example, * 1.25 to brighten it)

Marc Gravell
This works, but doesn't actually give precise values for percuptual colour values. I'd suggest having a look at Richard or dommer's answer for details of the HSL/HSV colour model.
Ant
+3  A: 

Here's some C# code for the conversions Richard mentioned:

RGB to HSL / HSL to RGB in C#

dommer
+2  A: 

You could also try using

ControlPaint.Light(baseColor, percOfLightLight)

ControlPaint.Light

or

ControlPaint.Dark(baseColor, percOfDarkDark)

ControlPaint.Dark

Alex
thanks...I didn't know that ControlPaint class was avalible
Brad