如何引用“newcommand”中定义的参数?

如何引用“newcommand”中定义的参数?

我在做什么:
我想画一张图(如下图所示)来说明一些区间收缩为一条线上的节点。
间隔

首先,我定义一个newcommandfor 区间(即 \op),它有三个参数:起点、终点和名称。然后,绘制一条线(或链)。最后,将区间和线中对应的节点连接起来。整个代码如下:(笔记:您还可以阅读和修改共享代码共享Latex才接受任何答案。)

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{tikz}
\usetikzlibrary{calc, chains}

\title{Reference Arguments in Newcommand}
\author{hengxin}
\date{31 December 2013}

\begin{document}
\begin{tikzpicture}[]

% new command: inverval
\newcommand{\op}[3] % #1: start point; #2: end point; #3: interval name
{
  \coordinate (start) at #1;    % start point
  \coordinate (end) at #2;  % end point
  \coordinate (mid) at ($0.5*#1 + 0.5*#2 + (0,0.8cm)$);

  \draw[ultra thick, blue, |-|] (start) -- (end); % draw the interval
  \node (#3) [font = \huge] at (mid) {#3};  % attach the operation name
}

% define three intervals
\op{(0,2)}{(2,2)}{$a$};
\op{(4,3)}{(6,3)}{$b$};
\op{(7,2)}{(10,2)}{$c$};

% contract them into single nodes in a line (or a chain)
\begin{scope}[font = \huge, start chain = schedule, node distance = 3.0cm, every     join/.style = {very thick, ->, red}]
  \foreach \opi in {a, b, c}
    \node (\opi) [circle, draw, on chain, join, label = {[] below : $\opi$}] {};
\end{scope}

% connect interval and its corresponding node in the line
\begin{scope}[cedge/.style = {->, dashed, draw, thick}]
  \draw [cedge] (0,2) to (a);
  \draw [cedge] (2,2) to (a);

  \draw [cedge] (4,3) to (b);
  \draw [cedge] (6,3) to (b);

  \draw [cedge] (7,2) to (c);
  \draw [cedge] (10,2) to (c);
\end{scope}

\end{tikzpicture}
\end{document}

我想做的事:
如你所见,在最后一步(连接区间和线中对应的节点)中,我已经像 一样硬编码了每个区间的起点和终点的坐标\draw [cedge] (0,2) to (a); \draw [cedge] (2,2) to (a);。这肯定很繁琐,而且容易出错。因此,

是否有一些优雅的方法可以让我引用每个间隔的两个点(作为的参数newcommand),而无需硬编码?

答案1

在您的\op命令中,您可以命名间隔的每个限制(使用#3作为名称的一部分)。

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc, chains}
\begin{document}
\begin{tikzpicture}
  % new command: inverval
  \newcommand{\op}[3]{ % #1: start point; #2: end point; #3: operation name
    \coordinate (start #3) at #1;   % start point
    \coordinate (end #3) at #2; % end point

    \draw[ultra thick, blue, |-|] (start #3) -- (end #3) % draw the interval
    node[pos=.5,above=8mm,font=\huge, text=black] {$#3$}; % attach the operation name
  }
  % define three intervals
  \op{(0,2)}{(2,2)}{a};
  \op{(4,3)}{(6,3)}{b};
  \op{(7,2)}{(10,2)}{c};
  % contract them into single nodes in a line (or a chain)
  \begin{scope}[font=\huge, start chain=schedule, node distance=3.0cm,
    every join/.style={very thick, ->, red}]
    \foreach \opi in {a, b, c} {
      \node [circle,draw,on chain,join,label={[]below:$\opi$}] (\opi) {};
    }
  \end{scope}
  % connect interval and its corresponding node in the line
  \begin{scope}[cedge/.style = {->, dashed, draw, thick}]
    \foreach \interval in {a,b,c}{
      \draw [cedge] (start \interval) to (\interval);
      \draw [cedge] (end \interval) to (\interval);
    }
  \end{scope}
\end{tikzpicture}
\end{document}

相关内容