![TikZ 中使用内部 sep=0pt 的边界框问题](https://linux22.com/image/478139/TikZ%20%E4%B8%AD%E4%BD%BF%E7%94%A8%E5%86%85%E9%83%A8%20sep%3D0pt%20%E7%9A%84%E8%BE%B9%E7%95%8C%E6%A1%86%E9%97%AE%E9%A2%98.png)
也许这是一个众所周知的问题,但我还没有找到解决方案。inner sep=0pt
节点上的 TikZ 选项会导致错误的边界框(至少对于字符或数字作为参数)。这意味着例如节点无法正确定位。在我的最小示例中,我试图说明这一点。以下是代码
\documentclass[tikz, border=2pt]{standalone}
\begin{document}
\begin{tikzpicture}
% If the bounding boxes were correct, the two ones would have to touch each other.
\node[fill=yellow, inner sep=0pt] (one) {1};
\node[fill=red, inner sep=0pt, anchor=west] at (one.east) {1};
\end{tikzpicture}
\end{document}
输出如下
如您所见,这两个的边界框在左侧和右侧部分太大,但在上部太小。下部符合我的预期。边界框表现如此的原因是什么?我在这里看到过https://stackoverflow.com/questions/47048850/font-bounding-box-and-glyph-bounding-box 之间有什么区别字体边界框和字形边界框之间存在差异。但在这两种定义中,边界框剪切其自身内容都是没有意义的,如本例所示。
答案1
水平空白来自/pgf/outer [xy]sep
s这.5\pgflinewidth
意味着锚点将位于绘制的边框的外侧。
对于未绘制的节点,您希望这些值为零,即outer sep = +0pt
。但是 PGF/TikZ 具有内置自动功能,可以检测未绘制的节点并通过指定将其设置为零
outer sep = auto
至于垂直重叠,PGF/TikZ 对此无能为力。它只考虑 TeX 报告的边界框。它不知道任何字形、字符或字体。
比较\fbox
显示相同的实例。
代码
\documentclass[varwidth, border=2pt]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[outer sep=auto]
\node[fill=yellow, inner sep=0pt] (one) {1};
\node[fill=red, inner sep=0pt, anchor=west] at (one.east) {2};
\end{tikzpicture}
\setlength{\fboxrule}{.01pt}%
\setlength{\fboxsep}{-\fboxrule}%
\fbox{1}\fbox{2}\fbox{O}
\end{document}
输出
答案2
请记住,即使您在声明节点时没有绘制其框,也会通过添加其厚度将其添加到框的计算中,因此解决方案是默认为这些节点定义与线宽相等的分隔,对于这种情况,尝试了几个选项后我发现它是 0.21pt,或者您也可以省去这项工作,将线条涂成与填充相同的颜色。
结果:
梅威瑟:
\documentclass[tikz, border=2pt]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
%Grid in pt units
\draw[black!30,step=1pt,line width=0.1pt] (0,0) grid (30pt,-30pt);
\draw[black!80,step=10pt,line width=0.2pt] (0,0) grid (30pt,-30pt);
\draw[|-|,line width=0.2pt] (0,0)++(0,3pt)-- ++(10pt,0) node[midway](n){};
\draw[<-] (n.center) |- ++(10pt,5pt) node [anchor=180, inner sep=0pt]{\tiny \verb+10pt+};
\node[fill=yellow, inner sep=0pt,anchor=south west] (one) at (0,-10pt) {1};
\node[fill=red, inner sep=0pt, anchor=west] at (one.east) {1};
\node[fill=yellow,draw=red, inner sep=0pt, anchor=south west, below=10pt of one](two){2};
\node[fill=red,draw=green, inner sep=0pt, anchor=west] at (two.east) {2};
\node[fill=yellow,draw=red, inner sep=0.21pt, anchor=south west, right=10pt of one,line width=0pt](three){3};
\node[fill=red,draw=green, inner sep=0.21pt, anchor=west,line width=0pt] at (three.east) {3};
\node[fill=blue, draw=blue,inner sep=0pt, anchor=south west, below=10pt of three](four){4};
\node[fill=orange, draw=orange,inner sep=0pt, anchor=west] at (four.east) {4};
\end{tikzpicture}
\end{document}