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

前端 未结 11 1409
春和景丽
春和景丽 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 19:10

    You can also simply work on the RGB percentage to get it lighter or darker as you want, Here is an example for how to make a color darker x% than it is:

    //_correctionfactory in percentage, e.g 50 = make it darker 50%
        private Color DarkerColor(Color color, float correctionfactory = 50f)
        {
            const float hundredpercent = 100f;                        
            return Color.FromArgb((int)(((float)color.R / hundredpercent) * correctionfactory),
                (int)(((float)color.G / hundredpercent) * correctionfactory), (int)(((float)color.B / hundredpercent) * correctionfactory));
        }
    

    One more thing we can also reverse the process to be lighter instead, Only we getting the result of 255 - RGB and then multiply it by the percentage we want like the following example:

    private Color LighterColor(Color color, float correctionfactory = 50f)
        {
            correctionfactory = correctionfactory / 100f;
            const float rgb255 = 255f;
            return Color.FromArgb((int)((float)color.R + ((rgb255 - (float)color.R) * correctionfactory)), (int)((float)color.G + ((rgb255 - (float)color.G) * correctionfactory)), (int)((float)color.B + ((rgb255 - (float)color.B) * correctionfactory))
                );
        }
    

    Hope that helps.

提交回复
热议问题