通过 for 循环中生成的名称引用 \pic

通过 for 循环中生成的名称引用 \pic

我使用循环放置图片列表,每个图片都有一个边界框。然后我引用其中一个边界框,但 tikz 似乎没有获取由 for 循环生成的名称。这是代码:

\documentclass[tikz]{standalone}
\usepackage{tikz}

\begin{document}

\tikzset{
 pics/circle/.style args={#1}{
   code = { 
        \node[circle, draw, color=red] at (0, 0){#1};
   }   
 },
}

\begin{tikzpicture}

\foreach \ind in {1,2,3,4}
{
    \pic [local bounding box=circ\ind] at (\ind, 0) {circle};
}

%% This one does not work
%\draw (0, 2) -- (circ2);

%% (3, 1) should connect to the second circle only, but it connects all 
\foreach \ind in {1,2,3,4}
    \draw(3, 1) -- (circ2);

\end{tikzpicture}
\end{document}

在此处输入图片描述

更新:最终,我找到了一种使用fit box的方法,这样我就不需要修改我的照片了(我自己的照片有点复杂)。

\documentclass[tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit}

\begin{document}

\tikzset{
 pics/circle/.style args={#1}{
   code = {
        \node[circle, draw, color=red] at (0, 0){#1};
   }
 },
}

\begin{tikzpicture}

\foreach \ind in {1,2,3,4}
{
    \pic [local bounding box=pic\ind] at (\ind, 0) {circle};
    %%% This is the trick
    \node [inner sep=0, fit=(pic\ind)] (circ\ind) {};
}

% This line works now
\draw (0, 2) -- (circ2);

%% (3, 1) should connect to the second circle only, but it connects all
\foreach \ind in {1,2,3,4}
    \draw(3, 1) -- (circ2);

\end{tikzpicture}
\end{document}

答案1

通常的问题是,\foreach循环的每个循环都在一个组内执行,而循环中所做的设置在该组结束后就会丢失。

我可以提供一个\listloop宏,其中循环索引用表示#1并且不使用分组,因为重新定义命令(例如)没有风险\ind

\documentclass[border=4]{standalone}
\usepackage{tikz}

\tikzset{
  pics/circle/.style args={#1}{
    code = { 
      \node[circle, draw, color=red] at (0, 0){#1};
    }
  },
}

\ExplSyntaxOn
\NewDocumentCommand{\listloop}{mm}
 {
  \clist_map_inline:nn { #1 } { #2 }
 }
\ExplSyntaxOff

\begin{document}

\begin{tikzpicture}

\listloop{1,2,3,4}{
    \pic [local bounding box=circ#1] at (#1, 0) {circle};
}

\draw (0, 2) -- (circ2);

\foreach \ind in {1,2,3,4}
    \draw(3, 1) -- (circ2);

\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

如果我理解了你想要什么,我认为你可以通过\coordinate在图片描述中添加一个来解决,使用相同(或另一个)参数。而且你可能不需要 las \foreach

\documentclass[tikz]{standalone}
\usepackage{tikz}

\begin{document}
\tikzset{
  pics/circle/.style args={#1}%
  {
    code =
    {
      \coordinate (circ#1) at (#1,0);
      \node[circle, draw, color=red] at (#1,0){#1};
    }   
  }
}

\begin{tikzpicture}
\foreach\ind in {1,2,3,4}
{
  \pic [local bounding box=outer box] {circle=\ind};
}

\draw (0, 2) -- (circ2);
% (3, 1) should connect to the second circle only, but it connects all 
% Then you probably don't need the following foreach
%\foreach \ind in {1,2,3,4}
\draw(3, 1) -- (circ2);
\end{tikzpicture}
\end{document}

使用上述代码你可以获得:

在此处输入图片描述

相关内容