2

I'm creating a custom beamer theme and defined a command to set the colors used in the presentation like that: \definecolor{primarycolor}{HTML}{9C27B0} (purple btw).
Let's say primarycolor is my background color of a frame.

Now, I want to be able to calculate the brightness/luminance of a given color to determine a fitting color for the text (either black or white). In the case of purple, white would be a readable text-color.

I would do it like that (pseudo-code):
luminance := 0.2126 * Red + 0.7152 * Green + 0.0722 * Blue
textcolor := luminance < 128 ? black : white

How do I get the RGB values of a color and then determine the "contrast-color" (black or white)?

  • Does \definecolor{mycolor}{RGB}{0,32,96} [interval [0,255]] or \definecolor{mycolor}{rgb}{0.2, 0.7, 0.7} [interval [0,1]] help in combination with \selectcolormodel{gray}(converts color to black-and-white) . Needs \usepackage{xcolor}. – Bobyandbob Jul 9 '17 at 15:22
  • Is there some way to compare colors by luminance then? Like, if the converted color is less-brighter/brighter than some other color. I'd like to define the text-colors on my own - it doesn't have to be black/white. – Nex Jul 9 '17 at 15:26
  • Is this what you would like to have tex.stackexchange.com/q/35033/3235 ? – percusse Jul 9 '17 at 15:35
1

Here's my solution to determine the luminosity of a color and then decide on a contrast-color (it's not clean but it works):

\RequirePackage{xcolor, etoolbox, xstring}
\definecolor{LightBlue}{HTML}{03A9F4}
\extractcolorspecs{grayScaleColor}{\modelspec}{\grayscale}


\StrBehind[1]{\grayscale}{0.}[\nbrstring]
\StrLeft{\nbrstring}{1}[\nbr]
\ifnumcomp{\nbr}{>}{5}{ % Brighter
    \colorlet{primary-text-color}{black}
}{ % Less bright
  \colorlet{primary-text-color}{white}
}
1

I just needed similar feature. This solution requires PGF

\newcommand{\setcolor}[3]{%
  \definecolor{#1}{HTML}{#3}%
  \extractcolorspecs{#1}{\modelspec}{\grayscale}%
  \pgfmathparse{(
    array({\grayscale},0)*0.2126+
    array({\grayscale},1)*0.7152+
    array({\grayscale},2)*0.0722)>=0.5?int(1):int(0)}%
  \ifnum\pgfmathresult>0%
    \colorlet{#2}{black}%
    \else%
    \colorlet{#2}{white}%
  \fi%
}%

You can call with:

\setcolor{my-background-color}{my-foreground-color}{377EB8}

It only works with HTML color definition but I thinks this can be easily extended.

Hope that help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.