有没有一种方法可以使 tikz 节点的顶部和底部具有不同的内部 ysep?
似乎没有简单的选择,但如果有人能提出一个技巧,那就太好了!
答案1
欢迎!有两种方法可以获得类似的结果。您可以使用fit
和移动拟合节点(节点 A 和 B),也可以使用text height
和text depth
(节点 C)。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\node[inner xsep=2pt,inner ysep=4pt,draw,anchor=base] at (-1,0) (Z){Z};
\node[inner sep=0pt,draw,anchor=base] (A){A};
\node[inner ysep=4pt,inner xsep=2pt,yshift=3pt,fit=(A),draw]{};
\node[inner sep=0pt,anchor=base] at (1,0) (B){B};
\node[inner ysep=4pt,inner xsep=2pt,yshift=3pt,fit=(B),draw]{};
\node[inner xsep=2pt,inner ysep=0pt,text height={height("C")+7pt},text depth=1pt,draw,anchor=base] at (2,0) (C){C};
\end{tikzpicture}
\end{document}
A 的内框只是为了引导眼睛。
可以通过创建样式来使其更加通用,asymmetric fit
。不对称拟合将从节点继承名称,并且您可以根据需要使用 pgf 键设置、 和upper ysep
。lower ysep
初始值为。left xsep
right xsep
2pt
\tikzset{afit/aset={upper ysep=8pt,style={draw}}}
\path node[asymmetric fit] (node0){Z};
完整代码:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\tikzset{asymmetric fit/.style={inner sep=0pt,append after command={
node[fit=(\tikzlastnode),afit/node style,outer sep=0pt,
inner ysep=\pgfkeysvalueof{/tikz/afit/upper ysep}/2+\pgfkeysvalueof{/tikz/afit/lower ysep}/2,
inner xsep=\pgfkeysvalueof{/tikz/afit/left xsep}/2+\pgfkeysvalueof{/tikz/afit/right xsep}/2,
yshift=\pgfkeysvalueof{/tikz/afit/upper ysep}/2-\pgfkeysvalueof{/tikz/afit/lower ysep}/2,
xshift=\pgfkeysvalueof{/tikz/afit/left xsep}/2-\pgfkeysvalueof{/tikz/afit/right xsep}/2,
](\tikzlastnode){}
}},
afit/.cd,upper ysep/.initial=2pt,lower ysep/.initial=2pt,
left xsep/.initial=2pt,right xsep/.initial=2pt,node style/.style={},
style/.code=\tikzset{afit/node style/.style={#1}},
aset/.code=\tikzset{afit/.cd,#1}}
\begin{document}
\begin{tikzpicture}
\tikzset{afit/aset={upper ysep=8pt,style={draw}}}
\path node[asymmetric fit] (node0){Z};
\draw[red] (node0.north east) -- ++ (1,0) -- (node0.south east);
\end{tikzpicture}
\end{document}
如果您想使用以下方法来简化这一过程\pgfextra
:请不要这样做,因为这可能会产生无法控制的副作用。
当然你可以赋予节点不同的名称。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\node[inner xsep=2pt,inner ysep=4pt,draw,anchor=base] at (-1,0) (node0){Z};
\node[inner sep=0pt,draw,anchor=base] (node1){A};
\node[inner ysep=4pt,inner xsep=2pt,yshift=3pt,fit=(node1),draw] (node2) {};
\node[inner sep=0pt,anchor=base] at (1,0) (node3){B};
\node[inner ysep=4pt,inner xsep=2pt,yshift=3pt,fit=(node3),draw] (node4) {};
\node[inner xsep=2pt,inner ysep=0pt,text height={height("C")+7pt},text depth=1pt,draw,anchor=base] at (2,0) (node5){C};
\end{tikzpicture}
\end{document}
答案2
另一个技巧可能是使用节点label
:
\documentclass[tikz, margin=3mm]{standalone}
\begin{document}
\begin{tikzpicture}[
box/.style = {draw, minimum size=7mm}
]
\node[box] {A};
\node[box, label={[anchor=north]above:B}] at (1,0) {};
\node[box, label={[anchor=south]below:C}] at (2,0) {};
\end{tikzpicture}
\end{document}