是否可以访问数组并使用其某个元素来指定 TikZ 中的最后一个迭代点\foreach
?
我尝试使用下面的代码但一直收到编译错误:
! Argument of \pgffor@@dotscharcheck has an extra }.
<inserted text>
\par
l.49 }
这是一个简单的例子:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{positioning}
\begin{document}
\begingroup
\newdimen\bitSize
\bitSize=2mm
\newdimen\bitSep
\bitSep=0.5mm
\newdimen\bitBigSep
\bitBigSep=3mm
\begin{tikzpicture}[%
auto,
every node/.style={%
node distance=0pt,
},
bit/.style={%
draw,
rectangle,
minimum size=\bitSize,
inner sep=0pt,
node distance=\bitSep,
},
]
\def\numBits{{4, 8, 4}}
\foreach \i in {1, 2, 3} {%
\pgfmathtruncatemacro\prevI{\i-1}
\foreach \j in {1, ..., \numBits[\prevI]} {%
\pgfmathtruncatemacro\prevJ{\j-1}
% Draw bit
\ifnum \j=1
\ifnum \i=1
\node [bit] (bit\i-\j) {};
\else
\node [bit, right=\bitBigSep of bit\prevI-\numBitsArray[\prevI-1]]
(bit\i-\j) {};
\fi
\else
\node [bit, right=of bit\i-\prevJ] (bit\i-\j) {};
\fi
}
}
\end{tikzpicture}
\endgroup
\end{document}
答案1
对于任何感兴趣的人,下面是我解决问题的方法:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{positioning}
\begin{document}
\begingroup
\newdimen\bitSize
\bitSize=2mm
\newdimen\bitSep
\bitSep=0.5mm
\newdimen\bitBigSep
\bitBigSep=3mm
\begin{tikzpicture}[%
auto,
every node/.style={%
node distance=0pt,
},
bit/.style={%
draw,
rectangle,
minimum size=\bitSize,
inner sep=0pt,
node distance=\bitSep,
},
]
\def\numBitsList{4, 16, 4}
\def\numBitsArray{{\numBitsList}}
\foreach \n [count=\i] in \numBitsList {%
\pgfmathtruncatemacro\prevI{\i-1}
\pgfmathparse{\numBitsArray[\prevI]} \let\numBits\pgfmathresult
\foreach \j in {1, ..., \numBits} {%
\pgfmathtruncatemacro\prevJ{\j-1}
% Draw bit
\ifnum \j=1
\ifnum \i=1
\node [bit] (bit\i-\j) {};
\else
\pgfmathparse{\numBitsArray[\prevI-1]} \let\pprevJ\pgfmathresult
\node [bit, right=\bitBigSep of bit\prevI-\pprevJ]
(bit\i-\j) {};
\fi
\else
\node [bit, right=of bit\i-\prevJ] (bit\i-\j) {};
\fi
}
}
\end{tikzpicture}
\endgroup
\end{document}