当我们想要创建一个位置取决于其大小的节点时,我们可以
- 将此节点排版在一个框中;
- 获取尺寸信息;
- 丢弃盒子/节点;
- 计算适当的位置;
- 对节点重新排版并进行适当的定位。
例如(这不是现实世界的问题,但展示了其复杂性)
\documentclass[border=9,tikz]{standalone}
\begin{document}
\makeatletter
\tikz{
\draw(-4,4)--(0,0)--(4,4);
\foreach\sometext in{short,medium text,looooooooooog text,extra super outstanding text}{
\node[opacity=0,draw](X){\sometext};
\pgfpointdiff{\pgfpointanchor{X}{west}}{\pgfpointanchor{X}{east}}
\pgfmathsetmacro\thewidthofthenode{\pgf@x}
\node[above,draw]at(0,\thewidthofthenode pt/2){\sometext};
}
}
\end{document}
或者更复杂一点:
\documentclass[border=9,tikz]{standalone}
\begin{document}
\makeatletter
\tikz{
\draw(-4,4)foreach\i in{-19,...,20}{-|(.2*\i-.1,{abs(.2*\i)})};
\foreach\sometext in{short,medium text,looooooooooog text,extra super outstanding text}{
\node[opacity=0,draw](X){\sometext};
\pgfpointdiff{\pgfpointanchor{X}{west}}{\pgfpointanchor{X}{east}}
\pgfmathsetmacro\thewidthofthenode{round(\pgf@x/28.45274/.4)*.4}
\node[above,draw]at(0,\thewidthofthenode/2){\sometext};
}
}
\end{document}
问题是
是否可以通过定义一种样式来实现这一点smart positioning
,使得下面的代码给出与上面相同的结果?
\documentclass[border=9,tikz]{standalone}
\begin{document}
\tikzset{
smart positioning/.style={
% how to define this?
}
}
\tikz{
\draw(-4,4)--(0,0)--(4,4);
%\draw(-4,4)foreach\i in{-19,...,20}{-|(.2*\i-.1,{abs(.2*\i)})};
\foreach\sometext in{short,medium text,looooooooooog text,extra super outstanding text}{
\node[smart positioning,draw]{\sometext};
}
}
\end{document}
PS:如果您能重新定义一些内部宏(例如\pgfmultipartnode
),我们将不胜感激。但是,请不要修改该\tikz{...}
部分。实际问题涉及一些隐式/深度构造的节点。
答案1
这不是一个低级解决方案,我不确定这是否是您正在寻找的,但它在您的特定示例中有效......我用它smart positioning={draw=red}
来代替“小”的差异smart positioning, draw=red
。
\documentclass[tikz,border=7pt]{standalone}
\makeatletter
\tikzset{
smart positioning/.style={
overlay,opacity=0,draw=none,fill=none,
append after command = {
\pgfextra{
\pgfpointdiff{\pgfpointanchor{\tikzlastnode}{west}}{\pgfpointanchor{\tikzlastnode}{east}}
\pgfmathsetmacro\thewidthofthenode{round(\pgf@x/28.45274/.4)*.4}
}
node[above,#1] at (0,\thewidthofthenode/2) {\sometext}
}
}
}
\makeatother
\begin{document}
\tikz{
\draw(-4,4)foreach\i in{-19,...,20}{-|(.2*\i-.1,{abs(.2*\i)})};
\foreach\sometext in{short,medium text,looooooooooog text,extra super outstanding text}{
\node[smart positioning={draw=red}]{\sometext};
}
}
\end{document}