C#: Create a lighter/darker color based on a system color

Viewed 90963
10 Answers

ControlPaint.Light .Dark .DarkDark, etc.

Color lightRed = ControlPaint.Light( Color.Red );

Here's some javascript code I use for lightening/darkening a given colour. You could use it as a base for an equivalent C# function

It works by calculating a distance from pure white of each of the RGB components and then adjusts this distance by the provided factor. The new distance is used to calculate the new colour. A factor of between 0 and 1 darkens, a factor higher than 1 lightens

function Darken( hexColor, factor )
    {   
        if ( factor < 0 ) factor = 0;

        var c = hexColor;
        if ( c.substr(0,1) == "#" )
        {
            c = c.substring(1);
        }

        if ( c.length == 3 || c.length == 6 )
        {
            var i = c.length / 3;

            var f;  // the relative distance from white

            var r = parseInt( c.substr(0, i ), 16 );
            f = ( factor * r / (256-r) );
            r = Math.floor((256 * f) / (f+1));

            r = r.toString(16);
            if ( r.length == 1 ) r = "0" + r;

            var g = parseInt( c.substr(i, i), 16);
            f = ( factor * g / (256-g) );
            g = Math.floor((256 * f) / (f+1));
            g = g.toString(16);
            if ( g.length == 1 ) g = "0" + g;

            var b = parseInt( c.substr( 2*i, i),16 );
            f = ( factor * b / (256-b) );
            b = Math.floor((256 * f) / (f+1));
            b = b.toString(16);
            if ( b.length == 1 ) b = "0" + b;

            c =  r+g+b;
         }   

         return "#" + c;

    }

Using HSI converter library(search google). And then, adjust I channel for lighter/darker color.

I changed Pavel Vladov function to modify even RGB component, to get shades on any combination of R/G/B directions:

Public Function ChangeColorShades(color As Color, correctionFactor As Single, bR As Boolean, bG As Boolean, bB As Boolean) As Color


    Dim red As Single = CSng(color.R)
    Dim green As Single = CSng(color.G)
    Dim blue As Single = CSng(color.B)

    If (correctionFactor < 0) Then

        correctionFactor = 1 + correctionFactor
        If bR Then
            red *= correctionFactor
        End If
        If bG Then
            green *= correctionFactor
        End If
        If bB Then
            blue *= correctionFactor
        End If


    Else
        If bR Then
            red = (255 - red) * correctionFactor + red
        End If
        If bG Then
            green = (255 - green) * correctionFactor + green
        End If
        If bB Then
            blue = (255 - blue) * correctionFactor + blue
        End If

    End If

    Return color.FromArgb(color.A, CInt(red), CInt(green), CInt(blue))
End Function
Related