![TikZ 中的 \pgfmath 和 \foreach](https://linux22.com/image/277979/TikZ%20%E4%B8%AD%E7%9A%84%20%5Cpgfmath%20%E5%92%8C%20%5Cforeach.png)
我对 TikZ 还很陌生。我有以下代码:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{chains}
\begin{document}
\begin{tikzpicture}[start chain=circle placed {at=(\tikzchaincount*30:1.5)},
regular/.style={draw,circle,inner sep=0,minimum size=4mm}]
\foreach \i in {0,...,11}
\node [on chain, regular] (\i) {\i};
\foreach \i in {0,...,11}
\draw [->] (\i) to ({\pgfmathparse{int(mod(\i+1,12))}\pgfmathresult});
\end{tikzpicture}
\end{document}
我原本想画出一系列均匀分布在圆上的 12 个节点,并在每两个相邻节点之间画一个箭头。LaTeX 给出了一条错误消息,指出
!incomplete \iffalse; all text was ignored after ...
做我想要做的事情的正确方法是什么?
答案1
在节点名称中使用宏时,宏必须在上下文中可展开\edef
。 \pgfmathparse
不是。因此,您需要事先进行计算,然后仅在节点名称中使用其结果。一种方法是使用evaluate
上的键,\foreach
如下所示。
\documentclass{article}
%\url{http://tex.stackexchange.com/q/141259/86}
\usepackage{tikz}
\usetikzlibrary{chains}
\begin{document}
\begin{tikzpicture}[start chain=circle placed {at=(\tikzchaincount*30:1.5)},regular/.style={draw,circle,inner sep=0,minimum size=4mm}]
\foreach \i in {0,...,11}
\node [on chain, regular] (\i) {\i};
\foreach[evaluate=\i as \ni using {int(mod(\i+1,12))}] \i in {0,...,11}
\draw [->] (\i) to (\ni);
\end{tikzpicture}
\end{document}
答案2
\documentclass[pstricks]{standalone}
\usepackage{pst-node,pst-plot}
\begin{document}
\begin{pspicture}[arrows=->,radius=12pt](-3,-3)(3,3)
\curvepnodes[plotpoints=13]{0}{360}{2.5 t 90 add PtoC}{P}% 90 is an angular offset
\multido{\i=0+1}{\Pnodecount}{\Cnodeput(P\i){A\i}{\i}}
\Cnodeput(P\Pnodecount){A\Pnodecount}{}
\multido{\ix=0+1,\iy=1+1}{\Pnodecount}{\ncline{A\ix}{A\iy}}
\end{pspicture}
\end{document}
动画片
\documentclass[pstricks]{standalone}
\usepackage{pst-node,pst-plot}
\begin{document}
\multido{\iN=4+1}{10}{%
\begin{pspicture}[arrows=->,radius=12pt](-3,-3)(3,3)
\curvepnodes[plotpoints=\iN]{0}{360}{2.5 t 90 add PtoC}{P}% 90 is an angular offset
\multido{\i=0+1}{\Pnodecount}{\Cnodeput(P\i){A\i}{\i}}
\Cnodeput(P\Pnodecount){A\Pnodecount}{}
\multido{\ix=0+1,\iy=1+1}{\Pnodecount}{\ncline{A\ix}{A\iy}}
\end{pspicture}}
\end{document}