我想以某种方式以编程方式确定 TikZ 图片的大小。有办法吗?这是一个简单的 MWE,我可以通过了解块大小并计算它们之间的节点距离来估计尺寸约为 8cm x 11cm。但更复杂的 TikZ 图片会使估计最终尺寸变得更加困难。
平均能量损失
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
[bigblock/.style={draw, rectangle, minimum size=5cm},
smallblock/.style={draw, rectangle, minimum size=2cm}
]
\node [bigblock] (box1) {};
\node [bigblock, above=of box1] (box2) {};
\node [smallblock, right=of box2] (box3) {};
\end{tikzpicture}
\end{document}
答案1
感谢评论中的@hpekristiansen 指出这个以 pt 为单位打印 TikZ 图片大小的答案:https://tex.stackexchange.com/a/137367/33388
我还将它与这里的答案结合起来,将 pts 转换为 cm:https://tex.stackexchange.com/a/137367/33388
平均能量损失
\documentclass[varwidth]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
%\show\pgfextractx
\newlength{\mywidth}
\newlength{\myheight}
\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
}
\def\convertto#1#2{\strip@pt\dimexpr #2*65536/\number\dimexpr 1#1}
\makeatother
\begin{document}
\begin{tikzpicture}
[bigblock/.style={draw, rectangle, minimum size=5cm, align=center},
smallblock/.style={draw, rectangle, minimum size=2cm, align=center}
]
\node [bigblock] (box1) {};
\node [bigblock, above=of box1] (box2) {};
\node [smallblock, right=of box2] (box3) {};
\pgfsize{\mywidth}{\myheight}
\end{tikzpicture}
% varwidth option was added to the standalone class options to allow for line breaks
Width = \convertto{cm}{\the\mywidth} cm\\
Height = \convertto{cm}{\the\myheight} cm
\end{document}