TikZ:节点角落处带有变量文本的标签的通用位置

TikZ:节点角落处带有变量文本的标签的通用位置

我想在 TikZ 中创建一个样式,在左上角绘制一个带有标签的节点。

问题是标签文本和节点宽度应该是可变的。下面是一个最小示例(我当前的方法),其中最后一个节点(nodename3)的标签位置不正确:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}
    \tikzset{genericnode/.style={rectangle, rounded corners=2pt, draw=black},
             mystyle/.style={genericnode, text width=15mm, fill=red!50,
                             label={[anchor=west, yshift=3pt, xshift=-9mm]{\tiny #1}}},
             vll/.style={mystyle=VeryLongLabel},
             sl/.style={mystyle=ShortL},}

    \node[vll]                                           (nodename)  {\tt text};
    \node[sl, below = 1cm of nodename]                   (nodename2) {\tt node with more lines};
    \node[sl, below = 1cm of nodename2, text width=35mm] (nodename3) {\tt node with more lines};
\end{tikzpicture}
\end{document}

在此处输入图片描述

你能给我一点提示吗?

答案1

您可以alias为主节点设置一个名称,并在标签选项中使用该名称来定位标签节点:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}
  \tikzset{
    genericnode/.style={rectangle, rounded corners=2pt, draw=black,},
    mystyle/.style={
      genericnode, text width=15mm, fill=red!50,
      alias=genericnode,% <- alias added
      label={[anchor=south west,shift={(genericnode.north west)},inner sep=2pt]{\tiny #1}}% position the label using the alias 
    },
    vll/.style={mystyle=VeryLongLabel},
    sl/.style={mystyle=ShortL},}

  \node[vll] (nodename) {\texttt{text}};
  \node[sl, below = 1cm of nodename] (nodename2) {\texttt{node with more lines}};
  \node[sl, below = 1cm of nodename2, text width=35mm] (nodename3) {\texttt{node with more lines}};
\end{tikzpicture}
\end{document}

结果:

在此处输入图片描述

相关内容