如何概括/简化这个注释命令?

如何概括/简化这个注释命令?

为了注释我的图形,我目前使用以下命令

\def\foolabellu[#1][#2](#3){%
  % synopsis
  % \foolabellu[text][length](endpoint)
  \coordinate (breakpoint) at ($(#3)+(-0.5,-0.5)$);
  \coordinate (startpoint) at ($(breakpoint)+(-#2, 0)$);
  \draw (startpoint) -- node[anchor=south west, pos=0, inner sep=0pt, yshift=0.15em] {#1\strut}  (breakpoint) -- (#3);
}
\def\foolabelru[#1][#2](#3){%
  \coordinate (breakpoint) at ($(#3)+(+0.5,-0.5)$);
  \coordinate (startpoint) at ($(breakpoint)+(#2, 0)$);
  \draw[thin] (startpoint) -- node[anchor=south east, pos=0, inner sep=0pt, yshift=0.15em] {#1\strut}  (breakpoint) -- (#3);
}
\def\foolabelld[#1][#2](#3){%
  \coordinate (breakpoint) at ($(#3)+(-0.5,+0.5)$);
  \coordinate (startpoint) at ($(breakpoint)+(-#2, 0)$);
  \draw (startpoint) -- node[anchor=south west, pos=0, inner sep=0pt, yshift=0.15em] {#1\strut}  (breakpoint) -- (#3);
}
\newcommand\foolabelrd{}
\def\foolabelrd[#1][#2](#3){%
  \coordinate (breakpoint) at ($(#3)+(+0.5,+0.5)$);
  \coordinate (startpoint) at ($(breakpoint)+(#2, 0)$);
  \draw[thin] (startpoint) -- node[anchor=south east, pos=0, inner sep=0pt, yshift=0.15em] {#1\strut}  (breakpoint) -- (#3);
}

在此示例中调用

\begin{tikzpicture}
  \node[draw, minimum width=2cm, minimum height=2cm] (rect) {};

  \foolabellu[\small left up][2.5](rect.south);
  \foolabelru[\small right up][2](rect.east);
  \foolabelld[\small left down][2.5](rect.west);
  \foolabelrd[\small right down][2](rect.north);
\end{tikzpicture}

产生这个

在此处输入图片描述

在我看来,使用四个命令是相当多余和多余的,但我无法理解如何更通用地为文本锚点执行此操作。此外,现在的编写方式不太灵活,例如,我想将起始节点用于其他用途。

是否有更规范/TikZish 的方法来实现这些注释?

答案1

该解决方案提供了一个\annotate具有当前 5 个参数的单个命令(我正在努力将它们减少到仅 2 个参数):

\annotate{ <node to annotate> }{ <top text> }{ <right> }{ <bottom> }{ <left> }

注释按顺时针方向进行,从顶部开始,如下所示:

在此处输入图片描述

如果其中一个text参数留空,则不会绘制任何内容,但会创建一条不可见的对角路径以保留一些空间。

输出

在此处输入图片描述

代码

\documentclass[margin=10pt]{standalone}
\usepackage{tikz}
\usepackage{xstring}

\usetikzlibrary{calc}

\newcommand\annotate[5]{%
    \foreach \nodanc/\anch/\text [
        count=\x starting from 0, 
        evaluate=\x as \ang using int(90*\x)
        ] in {%
        south west/north/{#2},
        south west/east/{#3},
        south east/south/{#4},
        south east/west/{#5}
    }{%
    \IfStrEq{\text}{}{%
        \path (#1.\anch) --++ ({45-\ang}:7mm);
    }{%
        \draw (#1.\anch) --++ ({45-\ang}:7mm) coordinate (a);
        \node[anchor=\nodanc, text width=2cm] (b) at (a) {\text};
        \draw (b.south west) -- (b.south east);
    }%
}}

\begin{document}
\begin{tikzpicture}
\node[draw, minimum width=2cm, minimum height=2cm] (rect) {};

\annotate{rect}{a long long text here}{}{left down}{left up}
\end{tikzpicture}
\end{document}

相关内容