我的问题比这个复杂得多,但要点非常相似。
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\foreach \x in {2,3,4} {\draw (A\x) -- (A\x-1);}
\end{tikzpicture}
\end{document}
问题是我需要使用\x
增加或减少(或计算)的变量并保持与 A 的联系。A\x
工作正常,但我无法开始A\x-1
工作。
答案1
用于(A\the\numexpr\x-1\relax)
以内联方式执行操作。
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\foreach \x in {2,3,4} {\draw (A\x) -- (A\the\numexpr\x-1\relax);}
\end{tikzpicture}
\end{document}
答案2
只需要一个坐标,就可以一次性画出线条:
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\draw (A1) \foreach \x in {2,3,4} {-- (A\x)};
\end{tikzpicture}
\end{document}
也会使关节更好,正如薛定谔的猫所说
答案3
将路径拆分成单个命令不是一个好主意\draw
,因为线连接看起来不太好。相反,我建议
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\draw plot[samples at={1,2,3,4}] (A\x);
\end{tikzpicture}
\end{document}