Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to generate colors that can easily be read on a white font?

Given either HSV or RGB, is there an algorithm that can prodice random colors for a background that are guaranteed to be readable on a pure white font?

It does not have to be a language specific implementation, though I am using C#.

Thanks

I made this, but I am sure it could be improved:

   public static System.Drawing.Color GenerateRandomLiteColor()
        {
            var rnd = new Random(DateTime.Now.Millisecond);
            double mul = 240.0;
            HSLColor c = new HSLColor(rnd.NextDouble() * mul,
                ((rnd.NextDouble() * 0.6) + 0.5) * mul, ((rnd.NextDouble() * 0.35) + 0.5) * mul);

            string s = c.ToRGBString();
            return c;
        }
like image 232
user2043533 Avatar asked Dec 06 '25 19:12

user2043533


2 Answers

Using HSL you could say anything with L below a certain value is visible, it has sufficient darkness for enough contrast. But this would be a subjective value. You could make H and S random. HSL can be then converted to HSV or RGB.

L should not be random. Or it could be but within a range that you have predefined to give sufficient contrast. ie below a fixed Lmax.

like image 120
QuentinUK Avatar answered Dec 09 '25 09:12

QuentinUK


For RGB there is a formula which calculates brightness of color:

0.299 * R + 0.587 * G + 0.114 * B

As you see each of R,G,B colors has its own brightness coefficient. To generate readable font on white background, generate completely random color. Then check if its brightness is less than some predefined constant C. If it exceeds C and equals to some D > C, then multiply each of R, G, B values by C / D to make the brightness equal to C.

like image 45
artahian Avatar answered Dec 09 '25 10:12

artahian