tikz 使用 pgfdeclare shape 自定义形状

tikz 使用 pgfdeclare shape 自定义形状

我希望定制一个仅绘制底部边框的节点。下面是我的代码:

\documentclass{standalone}
\usepackage{tikz}
\makeatletter
\pgfdeclareshape{mybox}{
    \inheritsavedanchors[from=rectangle]
    \inheritanchorborder[from=rectangle]
    \inheritbackgroundpath[from=rectangel]
    \foreach \i in {center,north,south,east,west,south east,south west} {
        \inheritanchor[from=rectangle]{\i}
    }
    \anchor{text} {
        \pgfpoint{-.5\wd\pgfnodeparttextbox}{-.5\ht\pgfnodeparttextbox}
    }
    \behindbackgroundpath{
        \northeast \pgf@xa=\pgf@x \pgf@ya=\pgf@y
        \southwest \pgf@xb=\pgf@x \pgf@yb=\pgf@y
        \pgfusepath{}
        \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
        \pgfpathlineto{\southwest}%
        \pgfpathclose
    }
    \foregroundpath{
        \pgfusepath{stroke}
    }
}
\makeatother
\begin{document}
    \begin{tikzpicture}
    \node[mybox] (A) {Text here};
    \end{tikzpicture}
\end{document}

当前逻辑可以绘制底线但不显示文本,输出上仅绘制了一行。

答案1

\documentclass[border=9pt]{standalone}
\usepackage{tikz}
\makeatletter
\pgfdeclareshape{mybox}{
    \inheritsavedanchors[from=rectangle]
    \inheritanchorborder[from=rectangle]
    \inheritbehindbackgroundpath[from=rectangle]
    \inheritforegroundpath[from=rectangle]
    \foreach \i in {center,north,south,east,west,south east,south west} {
        \inheritanchor[from=rectangle]{\i}
    }
    \inheritbeforeforegroundpath[from=rectangle]
    \inheritbehindforegroundpath[from=rectangle]
    \savedanchor{\upperrightcorner}{% 1127
      \pgf@yc=.5\ht\pgfnodeparttextbox % height of the box, ignoring the depth
      \pgf@xc=.5\wd\pgfnodeparttextbox % width of the box
    }
%     \anchor{text} {% manual explicitly says this is wrong (1129)
%         \pgfpoint{-.5\wd\pgfnodeparttextbox}{-.5\ht\pgfnodeparttextbox}
%     }
    \anchor{text}{% 1129
      \upperrightcorner%
      \pgf@x=-\pgf@xc%
      \pgf@y=-\pgf@yc%
    }
    \anchor{center}{\pgfpointorigin}
    \backgroundpath{
        \northeast \pgf@xa=\pgf@x \pgf@ya=\pgf@y
        \southwest \pgf@xb=\pgf@x \pgf@yb=\pgf@y
        \pgfpathmoveto{\pgfpoint{\pgf@xb}{\pgf@ya}}%
        \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@yb}}%
        \pgfpathlineto{\pgfpoint{\pgf@xa}{\pgf@yb}}%
        \pgfpathlineto{\pgfpoint{\pgf@xa}{\pgf@ya}}%
        \pgfpathmoveto{\pgfpoint{\pgf@xb}{\pgf@ya}}%
      }
}
\makeatother
\begin{document}
    \begin{tikzpicture} 
    \node[mybox,draw] (A) {Text here};
  \end{tikzpicture}
\end{document}

开箱

答案2

你需要一个新的形状吗?我认为path picture可以解决问题

\documentclass[border=2mm, tikz]{standalone}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}[
    mybox/.style={path picture={\draw[#1] (path picture bounding box.south west)--(path picture bounding box.south east);}}]

    \node[mybox] (a) {Text here};
    \node[mybox=red, right= of a] (b) {Another text here};
    \node[mybox={ultra thick, blue}, right= of b] (c) {And another one here};
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容