8

I'd like to use Tikz to algorithmically generate some text that has a color value based on calculations. Take the following, for example:

  \documentclass{standalone}
  \usepackage{tikz}
  \begin{document}
  \begin{tikzpicture}
      \foreach \i in {0, 1, ..., 10} {
          \draw (\i, 0) node {\textcolor[gray]{0.5}A};
      }
  \end{tikzpicture}
  \end{document}

This displays a row of "A"s in a gray:

enter image description here

How do I go about calculating the 0.5 value to, for example, display this set of "A"s in varying levels of gray, such as a black to white gradient? Could I use this same method to calculate arbitrary RGB values?

8

Yes, you can vary the gray levels, and the following can be used also to general non-gray colors.

\documentclass{standalone}
  \usepackage{tikz}
  \begin{document}
  \begin{tikzpicture}
      \foreach \i [evaluate=\i as \j using {int(\i*10)}] in {0, 1, ..., 10} {
          \draw (\i, 0) node[text=gray!\j!white] {A};
      }
  \end{tikzpicture}
  \end{document}

enter image description here

6

Just for fun, another foreach solution:

\documentclass{standalone}
  \usepackage{tikz}
  \begin{document}
  \begin{tikzpicture}
      \foreach \i [count=\j] in {0, 10, ..., 100} {
          \draw (\j, 0) node[text=blue!\i!red] {A};
      }
  \end{tikzpicture}
  \end{document}

enter image description here

5

You can evaluate a variable within the foreach loop itself (see page 904 of 3.0.1a manual).

Here since you want to go from black to white, you can do:

result

\documentclass{standalone}
  \usepackage{tikz}
  \begin{document}
  \begin{tikzpicture}
      \foreach \i [evaluate=\i as \gradient using 100-\i*10] in {0, 1, ..., 10} {
          \draw (\i, 0) node[text=black!\gradient] {A};
      }
  \end{tikzpicture}
  \end{document}
4

A slightly different syntax than what marmot proposed, but with the same effects

\documentclass[tikz,border=3.14pt]{standalone}
  \begin{document}
    \begin{tikzpicture}
      \draw foreach \i [evaluate=\i as \j using {int(\i*10)}] in {0, 1, ..., 10} {
          (\i, 0) node[text=gray!\j!white] {A}
      };
  \end{tikzpicture}
  \end{document}

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.