将值传递给命令

将值传递给命令

我是 Tikz 的新手,一直在遵循 PGFManual 来学习如何正确使用它。PGFManual 显示了使用示例foreach,但没有显示如何将其传递给命令。我正在编写的代码用四面体填充空间以定义烧绿石晶格。我声明命令以给定特定坐标来绘制四面体。

\newcommand{\tetra}[4]{
    \coordinate (A#1) at (#2+0.00,#3+0.00,#4+0.00);
    \coordinate (B#1) at (#2+0.00,#3+0.25,#4+0.25);
    \coordinate (C#1) at (#2+0.25,#3+0.00,#4+0.25);
    \coordinate (D#1) at (#2+0.25,#3+0.25,#4+0.00);
}

\newcommand{\drawtetra}[1]{
    \draw[lf line, opacity=1] (A#1)--(B#1)--(C#1)--cycle;
    \draw[df line, opacity=1] (A#1)--(B#1)--(D#1)--cycle;
}

然后在文档中调用它们来打印出我想要的四面体

\tetra{1}{0.00}{0.00}{0.00}
\tetra{2}{0.00}{0.50}{0.50}
\tetra{3}{0.50}{0.00}{0.50}
\tetra{4}{0.50}{0.50}{0.00}

\drawtetra{1}
\drawtetra{2}
\drawtetra{3}
\drawtetra{4}

我想通过以下方式实现该过程的自动化

foreach \i in {1,...,4}
    \drawtetra{\i}

这会产生一系列错误,主要与endcsname

我在网上没有找到任何解决方案,尽管我能找到的最接近的关系pgfkeys不幸的是我无法将其与我自己的程序联系起来。任何帮助都将不胜感激。生成图像的完整代码如下:

\documentclass{minimal}
\usepackage{tikz}
\usepackage{tikz-3dplot} %mentioned by Kevin C in comments
\usetikzlibrary{arrows}  %mentioned by Kevin C in comments

\newcommand{\tetra}[4]{
  \coordinate (A#1) at (#2+0.00,#3+0.00,#4+0.00);
  \coordinate (B#1) at (#2+0.00,#3+0.25,#4+0.25);
  \coordinate (C#1) at (#2+0.25,#3+0.00,#4+0.25);
  \coordinate (D#1) at (#2+0.25,#3+0.25,#4+0.00);
}

\newcommand{\drawtetra}[1]{
  \draw[lf line, opacity=1] (A#1)--(B#1)--(C#1)--cycle;
  \draw[df line, opacity=1] (A#1)--(B#1)--(D#1)--cycle;
}

\begin{document}
  \tdplotsetmaincoords{110}{70}
  \begin{tikzpicture}[
    scale = 12,
    axis/.style={very thick, ->, >=stealth'},
    df line/.style={thick, fill=darkgray!60, opacity=1},  %darkface
    lf line/.style={thick, fill=gray!30, opacity=1},      %lightface
    tdplot_main_coords
    ]

    \draw[axis] (0,0,0) -- (0,0,1);
    \draw[axis] (0,0,0) -- (0,1,0);
    \draw[axis] (0,0,0) -- (1,0,0);

    \tetra{1}{0.00}{0.00}{0.00}
    \tetra{2}{0.00}{0.50}{0.50}
    \tetra{3}{0.50}{0.00}{0.50}
    \tetra{4}{0.50}{0.50}{0.00}

    \drawtetra{1}
    \drawtetra{2}
    \drawtetra{3}
    \drawtetra{4}
  \end{tikzpicture}
\end{document}

答案1

您只是漏了一个分号。分号在 TikZ 中非常重要。事实上,可以说 TikZ 在这方面不像 LaTeX,而更像 C 或 Java。以下内容有效:

\foreach \i in {1,...,4} 
  \drawtetra\i;

您可以交替使用一个组,那么您就不需要分号了。

\foreach \i in {1,...,4} { 
  \drawtetra\i
}

相关内容