我想创建 32 个彼此相邻的小框,每个小框包含其当前索引。
|0|1|2|3|...|31|
这段代码让我很麻烦:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm}]
\node[box](0) {0};
\foreach \i in {0, 31} {
\node[box, right=of \i] (\i + 1) {\i+1};
}
\end{tikzpicture}
\end{document}
我的印象是 {\i+1} 未被解释,而是实际上为给定的 i 写入了 i+1。我怎样才能让 tikz 计算 i+1 并将结果指定为名称或标签?
答案1
是的,你的印象是对的。强制求值的一种方法是使用\numexpr
。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm}]
\node[box](0) {0};
\foreach \i in {0,..., 31} {
\node[box, right=of \i] (\the\numexpr\i + 1\relax)
{\the\numexpr\i+1\relax};
}
\end{tikzpicture}
\end{document}
不过,不太复杂的方法是使用评估。
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm}]
\node[box](0) {0};
\foreach \i [evaluate=\i as \nexti using {int(\i+1)}] in {0,..., 31} {
\node[box, right=of \i] (\nexti)
{\nexti};
}
\end{tikzpicture}
\end{document}
这是pic
其一个版本。
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm},
pics/boxrow/.style 2 args={code={
\node[box] (#1){#1};
\foreach \i [evaluate=\i as \nexti using {int(\i+1)}] in
{#1,\the\numexpr#1+1,...,#2} {
\node[box, right=of \i] (\nexti) {\nexti};
}
}}]
\path (0,0) pic{boxrow={0}{30}}
(0,-1) pic{boxrow={5}{18}};
\end{tikzpicture}
\end{document}
答案2
甚至还有另一种解决方案:
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm}]
\node[box](0) {0};
\foreach \i [remember=\i as \lasti (initially 0), count=\ni] in {1, ..., 31} {
\node[box, right=of \lasti] (\ni) {\ni};
}
\end{tikzpicture}
\end{document}
答案3
变体Ignasi 的回答您可以轻松更改范围的上限和下限\foreach
。
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm}
]
\foreach \i [remember=\i as \lasti (initially a)] in {0, ..., 31} {
\if a\lasti
\node[box](\i) {\i};
\else
\node[box, right=of \lasti](\i) {\i};
\fi
}
\end{tikzpicture}
\end{document}
答案4
一个更简单的解决方案是重复使用名称。
\documentclass{standalone}% too big for article
\usepackage{tikz}
%\usetikzlibrary{positioning}% not needed
\begin{document}
\begin{tikzpicture}[
node distance=0pt,
box/.style={outer sep=0pt, draw, thick, minimum height=0.6cm}]
\node[box](0) {0};
\coordinate (last) at (0.east);
\foreach \i in {1, ..., 31} {
\node[box, right] (\i) at (last) {\i};
\coordinate (last) at (\i.east);
}
\end{tikzpicture}
\end{document}