![在 TikZ 的嵌套 \foreach 循环中使用 \evaluate](https://linux22.com/image/241659/%E5%9C%A8%20TikZ%20%E7%9A%84%E5%B5%8C%E5%A5%97%20%5Cforeach%20%E5%BE%AA%E7%8E%AF%E4%B8%AD%E4%BD%BF%E7%94%A8%20%5Cevaluate.png)
我想使用 TikZ 并排绘制两个网格;左边是完整的方形网格,右边是下三角网格。我尝试编写以下代码来制作图形,但 \yy 始终等于 \y,并且它只绘制直线。我做错了什么?有没有更好的方法来绘制三角网格?
\begin{tikzpicture}
% Grid
\draw[step=1,color=gray] (0,0) grid (5,5);
% Pads
\draw (4.5,4.5) node {G};
\foreach \x [evaluate=\x as \ystart using int(\x-6), evaluate=\x as \xx using int(\x+1)] in {6, 7,..., 10}
\foreach \y [evaluate=\y as \yy using int(\y+1)] in {\ystart, ..., 4}
\draw [color=gray] (\x,\y) rectangle (\xx,\yy) node {\y, \yy} ;
% Pads
\draw (10.5,4.5) node {G};
\end{tikzpicture}
答案1
您需要将循环内容括\foreach
在花括号中:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
% Grid
\draw[step=1,color=gray] (0,0) grid (5,5);
% Pads
\draw (4.5,4.5) node {G};
\foreach \x [evaluate=\x as \ystart using int(\x-6), evaluate=\x as \xx using int(\x+1)] in {6, 7,..., 10}{
\foreach \y [evaluate=\y as \yy using int(\y+1)] in {\ystart, ..., 4}{
\draw [color=gray] (\x,\y) rectangle (\xx,\yy) node {\y, \yy} ;
}
}
% Pads
\draw (10.5,4.5) node {G};
\end{tikzpicture}
\end{document}