我正在尝试使用当前边界框计算 tikzpicture 的大小,但每次我尝试提取坐标时都会得到 0pt(对于所有内容)。
\documentclass{article}
\usepackage{tikz}
\newlength{\mywidth}
\newlength{\myheight}
% computes width and height of tikzpicture
\newcommand{\pgfsize}[2]{ % #1 = width, #2 = height
\pgfextractx{#1}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}}
{\pgfpointanchor{current bounding box}{north east}}}
\pgfextracty{#2}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}}
{\pgfpointanchor{current bounding box}{north east}}}
}
\begin{document}
\noindent
\begin{tikzpicture}
\draw node[rotate=90]{
\framebox{
\begin{tabular}{c|c}
first column & second column\\
\hline
1 & A\\
2 & B\\
$\vdots$ & $\vdots$
\end{tabular}
}};
\draw[color=red] (current bounding box.south west) -- (current bounding box.north east);
\pgfsize{\mywidth}{\myheight}
\end{tikzpicture}
\noindent
Width = \the\mywidth \\
Height = \the\myheight
\end{document}
如您所见,可以画一条线穿过边界框,因此它是存在的并且不平凡。我想我可能必须使用 \pgfgettransformentries,但什么时候?
答案1
A. Ellet 的评论是正确的:这是一个范围问题。是的,\mywidth
和\myheight
在环境范围内被分配了一个非零值tikzpicture
,但是,由于这些分配是本地的,它们的值仍然0pt
在该环境的范围之外。
\pgfsize
您可以通过在该宏的定义中将参数的分配设为全局(而不是局部)来解决该问题;见下文。本文由 Andrew Swan 撰写也应该感兴趣。
\documentclass{article}
\usepackage{tikz}
\show\pgfextractx
\newlength{\mywidth}
\newlength{\myheight}
% computes width and height of tikzpicture
\makeatletter
\newcommand{\pgfsize}[2]{ % #1 = width, #2 = height
\pgfextractx{\@tempdima}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}}
{\pgfpointanchor{current bounding box}{north east}}}
\global#1=\@tempdima
\pgfextracty{\@tempdima}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}}
{\pgfpointanchor{current bounding box}{north east}}}
\global#2=\@tempdima
}
\makeatother
\begin{document}
\noindent
\begin{tikzpicture}
\draw node[rotate=90]{
\framebox{
\begin{tabular}{c|c}
first column & second column\\
\hline
1 & A\\
2 & B\\
$\vdots$ & $\vdots$
\end{tabular}
}};
\draw[color=red] (current bounding box.south west) -- (current bounding box.north east);
\pgfsize{\mywidth}{\myheight}
\end{tikzpicture}
\noindent
Width = \the\mywidth \\
Height = \the\myheight
\end{document}