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

前端 未结 11 1443
春和景丽
春和景丽 2020-12-07 18:26

Duplicate

How do I adjust the brightness of a color?
How do I determine darker or lighter color variant of a given color?
Programmat

11条回答
  •  无人及你
    2020-12-07 18:54

    I recently blogged about this. The main idea is to apply a given correction factor to each of the color components. The following static method modifies the brightness of a given color with a specified correction factor and produces a darker or a lighter variant of that color:

    /// 
    /// Creates color with corrected brightness.
    /// 
    /// Color to correct.
    /// The brightness correction factor. Must be between -1 and 1. 
    /// Negative values produce darker colors.
    /// 
    /// Corrected  structure.
    /// 
    public static Color ChangeColorBrightness(Color color, float correctionFactor)
    {
        float red = (float)color.R;
        float green = (float)color.G;
        float blue = (float)color.B;
    
        if (correctionFactor < 0)
        {
            correctionFactor = 1 + correctionFactor;
            red *= correctionFactor;
            green *= correctionFactor;
            blue *= correctionFactor;
        }
        else
        {
            red = (255 - red) * correctionFactor + red;
            green = (255 - green) * correctionFactor + green;
            blue = (255 - blue) * correctionFactor + blue;
        }
    
        return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
    }
    

提交回复
热议问题