locked
Get a lighter version of a color RRS feed

  • Question

  • User1090916182 posted

    Suppose I create a variable holding a color value using FromHTML, then randomly create a second color using FromArgb, like so:

    Dim c1 As Color = ColorTranslator.FromHtml("#990000")
    Dim r As New Random
    Dim c2 As Color = Color.FromArgb(r.Next(200), r.Next(200), r.Next(200))

    Is it possible within the .Net framework to then create a slightly lighter version of those colours?  I know I could do this with c2 quite easily when it is created, but these colours are created in another section of my application, and I might not have access to the random values as they are created, hence my reason for asking.

    Thanks in advance.

    Wednesday, January 6, 2010 8:21 AM

Answers

  • User-964259575 posted

    You always have access to the red, green and blue values of the color, so a very simple algorithm for getting a lighter color could be like this.

    C#

    public Color GetLighterColor(Color color)
    {
        const int max = 255;
        int increase = 20;
    
        int r = Math.Min(color.R + increase, max);
        int g = Math.Min(color.G + increase, max);
        int b = Math.Min(color.B + increase, max);
    
        return Color.FromArgb(r, g, b);
    }

    VB

    Public Function GetLighterColor(color As Color) As Color
    	Const max As Integer = 255
    	Dim increase As Integer = 20
    
    	Dim r As Integer = Math.Min(color.R + increase, max)
    	Dim g As Integer = Math.Min(color.G + increase, max)
    	Dim b As Integer = Math.Min(color.B + increase, max)
    
    	Return Color.FromArgb(r, g, b)
    End Function
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 6, 2010 6:23 PM

All replies

  • User-964259575 posted

    You always have access to the red, green and blue values of the color, so a very simple algorithm for getting a lighter color could be like this.

    C#

    public Color GetLighterColor(Color color)
    {
        const int max = 255;
        int increase = 20;
    
        int r = Math.Min(color.R + increase, max);
        int g = Math.Min(color.G + increase, max);
        int b = Math.Min(color.B + increase, max);
    
        return Color.FromArgb(r, g, b);
    }

    VB

    Public Function GetLighterColor(color As Color) As Color
    	Const max As Integer = 255
    	Dim increase As Integer = 20
    
    	Dim r As Integer = Math.Min(color.R + increase, max)
    	Dim g As Integer = Math.Min(color.G + increase, max)
    	Dim b As Integer = Math.Min(color.B + increase, max)
    
    	Return Color.FromArgb(r, g, b)
    End Function
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 6, 2010 6:23 PM
  • User1090916182 posted

    Exactly what I was looking for!  I didn't know you could read the R,G,B values of a color.

    Thank you very much!

    Thursday, January 7, 2010 3:29 AM