开发者

How to pick good contrast RGB colors programmatically?

Suppose, in your program:

  1. color A is a color we randomly select

  2. Knowing color A, how can I pick a color B that will be in high contrast with color A?

The problem can be further reduced to: "imagine 2 squares filled with color next to one another. It should be unambiguously clear to a human eye that colors are not the same"

Example:


There is some information in the Web Content Accessibility Guidelines (WCAG) 2.0 (http://www.w3.org/TR/2008/REC-WCAG20-20081211)

  1. Visual contrast: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast

  2. Contrast ratio: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef

  3. Relative luminance : http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef

There's a good example in this site but he calculate where two colors are enough, not how to get them.

To choose a color with good contrast, I'd go with complementary colors: for example, choose the random color A, transform it to a HSV space, get the complementary hue.

Complementary hue: after you transform color from RGB to HSV, complementary hue will be 180 degrees appart (or 0.5, in a 0-1 normalized hue value). This site has something about it in PHP


As I was searching for a better way to do this, i stumbled across the Adobe Illustrator guide which mentions how they create complementary colors. They say:

Complement Changes each component of a color to a new value based on the sum of the highest and lowest RGB values in the selected color. Illustrator adds the lowest and highest RGB values of the current color, and then subtracts the value of each component from that number to create new RGB values. For example, suppose you select a color with an RGB value of 102 for red, 153 for green, and 51 for blue. Illustrator adds the high (153) and low (51) values, to end up with a new value (204). Each of the RGB values in the existing color is subtracted from the new value to create new complementary RGB values: 204 – 102 (the current red value) = 102 for the new red value, 204 – 153 (the current green value) = 51 for the new green value, and 204 – 51 (the current blue value) = 153 for the new blue value.

It wouldn't be too hard to do this programmatically and think this time that it might actually work for what you are trying to do.

Good Luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜