I want to draw a path where edges have alternating colors, like:
Ideally I want to use
\draw[red] (3,0)-- (3.5,0.5) -- (4,0.2) -- (4,-0.2) -- (3.5,-0.5) -- cycle;
But this can only specify a single color for the entire path. The best I can do is to use \path below then I need to repeat every coordinate twice, which is very awkward. I was wondering
(a) if this can accomplished in the style \draw + cycle as above by specifying the color of each edge along the way.
(b) if somehow the operation of alternating color can be automated, that would be even better!
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\path
(3,0) edge[blue] (3.5,0.5)
(3.5,0.5) edge[red] (4,0.2)
(4,0.2) edge[blue] (4,-0.2)
(4,-0.2) edge[red] (3.5,-0.5)
(3.5,-0.5) edge[blue] (3,0);
\end{tikzpicture}
\end{document}
Best Answer
You can use "append after command" to automatically repeat the coordinate. When you use
edge
tikz stores the target in\tikztotarget
, but this is in a local scope. By the time the "append after command" code is executed, the most recent coordinate has been forgotten. So theevery edge
code has to store the current value of\tikztotarget
in a global variable, using\global\let\currenttarget\tikztotarget
. Then we can append this usingappend after command
.In order to automatically alternate color, we use the standard tex "command that alternates between doing two things" pattern, but again because of scope issues you have to remember to do a global assignment.
For reference the relevant command is
\tikz@do@edge
which is defined on line 2912 of tikz.code.tex. The edge is drawn on line 2932 and our edge style code is evaluated there, theappend after command
code gets locally stored in\tikz@after@path
and is globally put into\tikz@after@path@smuggle
on line 2933. The scope then ends and the\tikz@after@path@smuggle
code is evaluated on line 2949.