Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

random - Programmatically choose high-contrast colors

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. When I am surfing between our development server and my local version of the C# code (redirected from the dev url via host file) I have been known to sometimes forget what 'dev.foo.com' points at - local or server.

So I created a page which will run locally as my default web page's default page, so I can easily identify my localhost from the server.

This page does a lot of things randomly (including generating a character's starting stats for D&D), including setting a random background color. I do this by generating 3 random numbers between 0 and 255, and setting them as the RGB value for the body background color in CSS.

Given the 3 ints R, G, and B, how do I determine R2, G2, and B2 such that the second color will have high contrast with the first? I like having the page have random background colors (it keeps me from getting used to the look of the landing page) but I also like to be able to read the text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need a difference in brightness for text to be readable, as color vision itself has too low resolution.

So as an algorithm I'd suggest the following:

  • Pick a random background color.

  • Then decide whether it is a light or a dark color. For example you could check whether the average of the three primary colors is greater or equal 128.

  • For a light color use black text, for a dark one white text.

Update: Here is an example image I made while playing with the split_evenly example of the Rust crate plotters. It shows the colors in Palette99:

7x3 colored fields with their index in either black or white depending on the background's brightness


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...