我想画出以下数字方块:
6 7 8
3 4 5
0 1 2
为此,我编写了以下 LaTeX 代码,并将其保存在文件中~\test.tex
:
\documentclass[tikz,border=1cm]{standalone}
\begin{document}
\tikz \foreach \r in {0,1,2}
\foreach \c [evaluate=\c as \n using {\r*3+\c}] in {0,1,2}
\node at (\c,\r) {\n};
\end{document}
当在终端中执行以下命令时:
cd ~
pdflatex 测试
命令执行pdflatex
失败,并~\test.log
包含以下代码片段:
! Package pgfkeys Error: I do not know the key '/pgf/foreach/2' and I am going
to ignore it. Perhaps you misspelled it.
See the pgfkeys package documentation for explanation.
Type H <return> for immediate help.
...
l.5 ...\r*3+\c}] in {0,1,2} \node at (\c,\r) {\n};
?
! Emergency stop.
...
l.5 ...\r*3+\c}] in {0,1,2} \node at (\c,\r) {\n};
End of file on the terminal!
我做错了什么?我该如何解决?
答案1
免责声明:这是我的另一个答案,而不是在我之前的答案下添加评论。
\tikz
当您只有单行命令时使用,例如\tikz \draw (0,0) -- (1,0);
。
如果您要编译多行命令,则必须在\begin{tikzpicture}
和之间创建一个范围\end{tikzpicture}
。
如果您在命令周围添加两对花括号,您的代码就可以正常工作:
\documentclass[tikz,border=1cm]{standalone}
\begin{document}
\tikz {\foreach \r in {0,1,2} {\foreach \c [evaluate=\c as \n using {int(\r*3+\c)}] in {0,1,2} \node at (\c,\r) {\n};}}
\end{document}
但将所有代码都包含在一个范围内会更好tikzpicture
,如下所示:
\documentclass[tikz,border=1cm]{standalone}
\begin{document}
\begin{tikzpicture}
\foreach \r in {0,1,2}
{
\foreach \c [evaluate=\c as \n using {int(\r*3+\c)}] in {0,1,2}
\node at (\c,\r) {\n};
}
\end{tikzpicture}
\end{document}
结果相同,但更清晰。
答案2
答案3
matrix
这也可以通过 a和 no来完成foreach
。
\documentclass[tikz, margin=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[%
arraynode/.style={
node contents={\the\numexpr3*(3-\pgfmatrixcurrentrow)+\pgfmatrixcurrentcolumn-1\relax},
},
array/.style={%
matrix of nodes,
nodes = arraynode,
nodes in empty cells},
]
\matrix[array] {
&&\\
&&\\
&&\\};
\end{tikzpicture}
\end{document}