让我们考虑以下代码。为什么 foreach 生成的路径部分与展开的部分看起来不一样?
\begin{tikzpicture}[
edge/.style = {
draw,
thick,
},
open/.style = {
draw,
circle,
thick,
inner sep = 0.09cm,
},
closed/.style = {
open,
fill,
},
]
\foreach \x in {1, 2, ..., 5} {
\node[closed] at (\x, 0) (c\x) {};
\node[open] at (\x + 0.5, 1) (o\x) {};
}
\node at (0.25, 0.5) (start) {$\cdots$};
\node at (6.25, 0.5) (end) {$\cdots$};
\path[edge] (start.east) foreach \x in {1, 2, 3} {-- (c\x) -- (o\x)} -- (c4) -- (o4) -- (c5) -- (o5) -- (end.west);
\end{tikzpicture}
答案1
\foreach
在循环体周围添加一个组级别。因此,我认为,最后一个点是开圆节点的信息丢失了,并且 TikZ 将线连接到最新绘制的线的终点。
这里有很多种使用方法\foreach
,因为这些线实际上并没有连接在一起。例如:
\path[edge]
(start.east) -- (c1)
\foreach \x in {1, 2, ..., 5} {
(c\x) -- (o\x)
\ifnum\x<5
-- (c\the\numexpr\x + 1\relax)
\fi
}
(o5) -- (end.west)
;
或者
\path[edge]
(start.east) -- (c1)
\foreach \x in {1, 2, ..., 5} {
(c\x) -- (o\x)
}
\foreach \x in {1, 2, ..., 4} {
(o\x) -- (c\the\numexpr\x + 1\relax)
}
(o5) -- (end.west)
;
答案2
我整理了以下参数化变体。
\begin{tikzpicture}[x=1.12cm]
\def \N {5}
\foreach \i in {1, ..., \N} {
\node[closed] (c\i) at (\i + 0.25, -0.5) {};
\node[open] (o\i) at (\i + 0.75, 0.5) {};
}
\path[edge] foreach \i in {1, ..., \N} {
(\i, 0) -- (c\i) -- (o\i) -- (\i + 1, 0)
};
\node[anchor=east] at (1 - 0.1, 0) {${\cdots}$};
\node[anchor=west] at (\N + 1 + 0.1, 0) {${\cdots}$};
\end{tikzpicture}