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)?

3
  • 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
    Commented Jul 9, 2017 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.
    – peterpf
    Commented Jul 9, 2017 at 15:26
  • Is this what you would like to have tex.stackexchange.com/q/35033/3235 ?
    – percusse
    Commented Jul 9, 2017 at 15:35

2 Answers 2

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .