[Tex/LaTex] Write text with negative color in tikz

colortikz-pgf

There is probably no simple and general solution to this, but is it possible in tikz to write text in the negative color of the background, whatever the background?

To illustrative the problem (but I am not asking for a solution specific to this background):

\documentclass[tikz]{standalone}

\begin{document}
\begin{tikzpicture}
\shade[left color=black,right color=red] (0,0) rectangle (4,2);
\node at (2,1) {this text is hard to read};
\end{tikzpicture}
\end{document}

enter image description here

Negative is to be understood in any sense (complementary color, complementary to black), it does not really matter. The idea is to get something readable for any background.

Edit This is a comparison of the different methods suggested.

  • First column: original (black text), 400 is not easy to read
  • Second column: what I requested: not a good idea at all!
  • Third column: white text with black contour: hardly readable when small
  • Fourth column: black text on white background with opacity: my favorite
  • Fifth column: white text in black background: I like it too, but slightly prefer the fourth one here because it's lighter.

enter image description here

Best Answer

The short answer is: use blend modes (p.340, pgfmanual v3.0.1a) with difference mode.

But, for better results, you may use outlined text or background with opacity. The following picture shows different tests:

enter image description here

\documentclass[tikz]{standalone}
\usepackage[outline]{contour}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
  \node (a) {\includegraphics{tiger}};

  \path (a.north) -- (a.south)
  \foreach \pos in {1,...,7}{coordinate[pos=\pos/8] (p-\pos)};

  \tikzset{my text/.style={text=white,font=\Huge\bfseries}}
  \def\mytext{Test of long text}

  \node[my text] (ex) at (p-1) {\mytext};
  \node[anchor=east] at (ex -| a.west) {white text};

  \node[my text,text=black](ex) at (p-2) {\mytext};
  \node[anchor=east] at (ex -| a.west) {black text};

  \node[my text,fill opacity=.5,fill=black,text opacity=1] (ex) at (p-3) {\mytext};
  \node[anchor=east] at (ex -| a.west) {black background with opacity};

  \node[my text,text=black,fill opacity=.5,fill=white,text opacity=1] (ex) at (p-4) {\mytext};
  \node[anchor=east] at (ex -| a.west) {white background with opacity};

  \node[my text] (ex) at (p-5) {\contour{white}{\mytext}};
  \node[anchor=east] at (ex -| a.west) {white outlined text};

  \node[my text] (ex) at (p-6) {\contour{black}{\textcolor{white}{\mytext}}};
  \node[anchor=east] at (ex -| a.west) {black outlined text};

  \begin{scope}[blend group=difference]
    \clip ($(p-7 -| a.west) + (0,1.1em)$) rectangle ($(p-7 -| a.east) + (0,-1.1em)$);
    \node {\includegraphics{tiger}};
    \node[my text] (ex) at (p-7) {\mytext};
  \end{scope}
  \node[anchor=east] at (ex -| a.west) {\emph{required} blended text (difference)};
\end{tikzpicture}
\end{document}