Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I adjust the brightness of a color?

Tags:

c#

gdi+

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+

like image 647
Brad Avatar asked Apr 10 '09 10:04

Brad


People also ask

Can you adjust RGB brightness?

To change the brightness, divide R, G and B through a number larger than 1 to make it darker, or multiply them with that number to make it brighter. If the color component becomes higher than 255, truncate it to 255.

How do I manually adjust brightness?

Open the Settings app from your Start menu or Start screen, select “System,” and select “Display.” Click or tap and drag the “Adjust brightness level” slider to change the brightness level. If you're using Windows 7 or 8, and don't have a Settings app, this option available in the Control Panel.


6 Answers

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)

like image 82
Marc Gravell Avatar answered Sep 29 '22 14:09

Marc Gravell


You could also try using

ControlPaint.Light(baseColor, percOfLightLight)

ControlPaint.Light

or

ControlPaint.Dark(baseColor, percOfDarkDark)

ControlPaint.Dark

like image 22
Alex Avatar answered Sep 26 '22 14:09

Alex


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

While System.Drawing.Color 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".

like image 30
Richard Avatar answered Sep 27 '22 14:09

Richard


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

RGB to HSL / HSL to RGB in C#

like image 42
dommer Avatar answered Sep 26 '22 14:09

dommer


While the aforementioned methods do darken the color but they adjust the hue way to much so the result doesn't look very good. The best answer is to use Rich Newman's HSLColor class and adjust the luminosity.

public Color Darken(Color color, double darkenAmount) {
    HSLColor hslColor = new HSLColor(color);
    hslColor.Luminosity *= darkenAmount; // 0 to 1
    return hslColor;
}
like image 38
TugboatCaptain Avatar answered Sep 29 '22 14:09

TugboatCaptain


You must keep track that the value does not extend below 0 or above 255

Best approach is to use Math.Max/Math.MIn

dim newValue as integer = ...
'correct value if it is below 0 or above 255
newValue = Math.Max(Math.Min(newValue,255),0)
like image 34
VB.net Coder Avatar answered Sep 28 '22 14:09

VB.net Coder