将节点作为参数传递给 TikZ 中的宏

将节点作为参数传递给 TikZ 中的宏

我想定义一个宏,它将两个节点作为参数,并使用第三个预定义节点“连接”它们。像这样:

\documentclass{minimal}

\usepackage{tikz}
\usetikzlibrary{shapes,positioning,fit}

\newcommand{\diamondconn}[3]{
  \node[diamond, draw, innter sep=2pt] (diamond) { #1 };
  % get the references to #2 and #3 and position them
  % on the left and right side of the `conn' node
}

\begin{document}

% instead of writing this...
\begin{tikzpicture}
  \node[diamond, draw, inner sep=2pt] (diamond) { conn };
  \node[draw, left=0pt of diamond.west] { foo };
  \node[draw, circle, right=0pt of diamond.east] { bar };
\end{tikzpicture}

% I would like to write this:
\begin{tikzpicture}
  \diamondconn{conn}{
    \node[draw, rectangle] { foo };
  }{
    \node[draw, circle] { bar };
  }
\end{tikzpicture}

\end{document}

我知道我可以反过来做,即为连接节点定义一个宏并在需要时插入它,我只是好奇第一个选项是否也可行。

答案1

我假设您希望将作为参数传递的节点定义与宏内部发生的情况无关(因此您不想left of=diamond.west在节点定义中明确使用)。为了实现这一点,您可以将在scope环境中传递的节点包装在宏内并“注入”定位选项,或者,正如 Martin Scharrer 所建议的那样,使用\tikzset花括号内来本地设置选项:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes,positioning,fit}

\newcommand{\diamondconn}[3]{

  \node[diamond, draw, inner sep=2pt] (diamond) { #1 };
  {\tikzset{every node/.style={left=0pt of diamond.west}} #2 }
  {\tikzset{every node/.style={right=0pt of diamond.east}} #3 } 
}

\begin{document}

\begin{tikzpicture}
  \diamondconn{conn}{
    \node[draw, rectangle] { foo };
  }{
    \node[draw, circle] { bar };
  }
\end{tikzpicture}

\end{document}

答案2

\documentclass{minimal}    
\usepackage{tikz}
\usetikzlibrary{shapes,positioning,fit}

\newcommand{\diamondconn}[3]{%    
  \node[diamond, draw, inner sep=2pt] (diamond) { #1 }; 
  #2#3 }

\begin{document}
\begin{tikzpicture}
  \diamondconn{conn}{
     \node[draw, left=0pt of diamond.west] { foo }; 
  }{%
   \node[draw, circle, right=0pt of diamond.east] { bar };
  }
\end{tikzpicture}    
\end{document} 

在此处输入图片描述

相关内容