Programmatically choose high-contrast colors

前端 未结 10 672
野的像风
野的像风 2020-12-14 07:29

This should be a simple question, but I haven\'t been able to find a way to make it work.

Essentially, I have a silly localhost page that I use in my webdevelopment.

相关标签:
10条回答
  • 2020-12-14 07:36
    private Color GetContrastingColor(Color color)
    {
        int r = color.R > 0 ? 256 - color.R : 255;
        int g = color.G > 0 ? 256 - color.G : 255;
        int b = color.B > 0 ? 256 - color.B : 255;
        return System.Drawing.Color.FromArgb(r, g, b);
    }
    
    0 讨论(0)
  • 2020-12-14 07:39

    Thanks to @starblue !

    Here is C# code that I use

     public static string GetContrastBlackOrWhiteColorAsHtmlColorCode(Color c)
            {
                System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("transparent");
    
                try
                {
                    if (c.R >= 128 && c.G >= 128 && c.B >= 128)
                    {
                        return System.Drawing.ColorTranslator.ToHtml(Color.Black);
                    }
                    else
                    {
                        return System.Drawing.ColorTranslator.ToHtml(Color.White);
                    }
                }
                catch (Exception)
                {
                }
    
                return System.Drawing.ColorTranslator.ToHtml(color);
            }
    
    0 讨论(0)
  • 2020-12-14 07:43

    You can use method GetBrightness() on Color class. It returns a float value from 0.0 (brightness of black) to 1.0 (white). A simple solution would be:

    var color1 = new Color.FromArgb(r1, g1, b1);
    var brightness = color1.GetBrightness();
    
    var color2 = brightness > 0.5 ? Color.Black : Color.White;
    
    0 讨论(0)
  • 2020-12-14 07:45

    Check out this PHP solution: Calculating Color Contrast with PHP by Andreas Gohr. It can be ported to any language of course.

    He also has a very nice demonstration of his contrast analyzer where you can find some minimal contrast levels to work with.

    0 讨论(0)
  • 2020-12-14 07:48

    If you flip all the bits, you will get the "opposite" color which would be pretty good contrast.

    I believe it's the ~ operator in C#:

    R2 = ~R1;
    G2 = ~G1;
    B2 = ~B1;
    
    0 讨论(0)
  • 2020-12-14 07:52

    These answers are more or less suggesting to use one of the two or three color choices based on whether the color is bright or dark.

    I use a bit different approach and it worked elegantly in my case. Here is the implementation.

     int color = your_color;
     contrastColor = Color.rgb(255-(color >> 16)&0xFF, 255-(color >> 8)&0xFF, 255- color&0xFF);
    

    It's simple and wonderful.

    0 讨论(0)
提交回复
热议问题