在 tikzpicture foreach 迴圈中使用 newcommands

在 tikzpicture foreach 迴圈中使用 newcommands

我嘗試在 TikZ 頁面中嵌套命令,以便我可以在每個層級使用少量程式碼來製作逐漸更複雜的東西。到目前為止我的程式碼是

\documentclass{article}
\usepackage{tkz-graph}

\newcommand{\drawSquare}[3]{%
  \draw[thick,#3] (#1-0.5,#2-0.5) rectangle (#1+0.5,#2+0.5);}
\newcommand{\boxesAtHeight}[3]{%
  \foreach \i in {1,...,#1}
    \drawSquare{\i}{#2}{#3}}

\begin{document}

\begin{tikzpicture}
  \boxesAtHeight{4}{0}{black}
  \boxesAtHeight{2}{1}{black}
  \boxesAtHeight{1}{2}{black}
\end{tikzpicture}

\end{document}

我使用 sharelatex,當我嘗試編譯時,出現 4 個錯誤。在之後的線路中\end{tikzpicture},我遇到了錯誤

段落在\pgffor@next完成之前就結束了。

在 行中\end{document},我得到了三個錯誤

缺少\endgroup插入。

缺少}插入。

LaTeX 錯誤:\begin{tikzpicture}輸入第 12 行以\end{document}.

tikzpicture當我透過擴展巨集替換 中的程式碼時\boxesAtHeight,我得到了相同的錯誤。

當我進一步擴展\drawSquare巨集時,我得到以下輸出

展開每個巨集後成功輸出

需要明確的是,第一次擴充產生了程式碼

\begin{tikzpicture}
  \foreach \i in {1,...,4}
    \drawSquare{\i}{0}{black}
  \foreach \i in {1,...,2}
    \drawSquare{\i}{1}{black}
  \foreach \i in {1,...,1}
    \drawSquare{\i}{2}{black}
\end{tikzpicture}

第二次擴充得到了程式碼

\begin{tikzpicture}
  \foreach \i in {1,...,4}
    \draw[thick,black] (\i-0.5,0-0.5) rectangle (\i+0.5,0+0.5);
  \foreach \i in {1,...,2}
    \draw[thick,black] (\i-0.5,1-0.5) rectangle (\i+0.5,1+0.5);
  \foreach \i in {1,...,1}
    \draw[thick,black] (\i-0.5,2-0.5) rectangle (\i+0.5,2+0.5);
\end{tikzpicture}

誰能向我解釋為什麼我會收到錯誤?我知道\drawSquare宏在循環之外工作。

答案1

您需要對 for 迴圈的主體進行分組:

\documentclass{article}
\usepackage{tkz-graph}

\newcommand{\drawSquare}[3]{%
  \draw[thick,#3] (#1-0.5,#2-0.5) rectangle (#1+0.5,#2+0.5);}
\newcommand{\boxesAtHeight}[3]{%
  \foreach \i in {1,...,#1}
    {\drawSquare{\i}{#2}{#3}}}%<== put the \drawSquare{\i}{#2}{#3} in {}

\begin{document}

\begin{tikzpicture}
  \boxesAtHeight{4}{0}{black}
  \boxesAtHeight{2}{1}{black}
  \boxesAtHeight{1}{2}{black}
\end{tikzpicture}

\end{document}

結果

相關內容