我有以下代码:
\documentclass[11pt]{article}
\usepackage[a4paper]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[node distance = 0.5cm, auto]
\node (0) {Block 0};
\node (1) [below= of 0.south] {Block 1};
\node (2) [below= of 1.south] {Block 2};
\end{tikzpicture}
\end{document}
它打印出以下内容:
我尝试使用 pgf 循环执行相同操作,但不知道如何减少计数器:
\foreach \x in {0,...,2}
{
\ifnum\x=0\relax
\node (\x) {Block \x};
\else
%\prev=\x - 1 <- ???
\node (\x) [below= of \prev.south] {Block \x};
\fi
}
答案1
你可以使用数学:)
\foreach \x in {0,...,2}{
\ifnum\x=0\relax
\node (\x) {Block \x};
\else
\pgfmathparse{int(\x-1)}
\node (\x) [below= of \pgfmathresult.south] {Block \x};
\fi
}
答案2
除了使用之外,\pgfmathparse{int(…)}
您还可以使用\pgfmathtruncatemacro
或:
- eTeX
\numexpr
的 \foreach
'sevaluate
(再次与int
),\foreach
的remember
,\foreach
的count
起始from -1
(即第\x
一个减一)- (推荐)
chains
带有 的库start chain=<chain name> going below
。
代码
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning,chains}
\tikzset{node distance=.5cm}
\begin{document}
\begin{tikzpicture}
\foreach \x in {0,...,2}{
\ifnum\x=0\relax
\node (\x) {Block \x};
\else
\node (\x) [below=of \number\numexpr\x-1\relax] {Block \x};
\fi
}
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x[evaluate=\x as \eval using int(\x-1)] in {0,...,2}{
\ifnum\x=0\relax
\node (\x) {Block \x};
\else
\node (\x) [below=of \eval] {Block \x};
\fi
}
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x[remember=\x as \eval] in {0,...,2}{
\ifnum\x=0\relax
\node (\x) {Block \x};
\else
\node (\x) [below=of \eval] {Block \x};
\fi
}
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x[count=\eval from -1] in {0,...,2}{
\ifnum\x=0\relax
\node (\x) {Block \x};
\else
\node (\x) [below=of \eval] {Block \x};
\fi
}
\end{tikzpicture}
\begin{tikzpicture}[start chain=going below]
\foreach \x in {0,...,2}
\node[on chain] (\x) {Block \x};
\end{tikzpicture}
\end{document}