访问 \parbox 的高度

访问 \parbox 的高度

在 中,\parbox 我可以通过 访问其宽度\linewidth(例如,如果我想放置与 一样宽的图像,这很有用\parbox)。有没有办法访问\parbox 当高度由可选参数固定时?(当然,只有在这种情况下这个问题才有意义。)

\documentclass{article}

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

% here I'd like something like \parboxheight or similar
\fbox{\parbox[][100pt][t]{100pt}{Some text, some more text, and \the\linewidth, and the height?}}

\end{document}

在此处输入图片描述

答案1

以下解决方案修补了\@iiiparbox第二个参数以获取高度。该值存储在尺寸寄存器中\parboxheight

如果未设置高度,LaTeX 将使用\relax此参数。然后,\parboxheight设置为零。如果您想知道高度参数是否设置为可选参数,可以使用附加开关。

例子:

\documentclass{article}

\newdimen\parboxheight

\makeatletter
\newcommand*{\org@iiiparbox}{}
\let\org@iiiparbox\@iiiparbox
\renewcommand*{\@iiiparbox}[2]{%
  \ifx\relax#2%
    \setlength{\parboxheight}{0pt}%
  \else
    \setlength{\parboxheight}{#2}%
  \fi
  \org@iiiparbox{#1}{#2}%
}
\makeatother

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

\fbox{%
  \parbox[][80pt][t]{100pt}{%
    \raggedright
    Some text, some more text, and width \the\linewidth, %
    and the height \the\parboxheight.%
  }%
}
\end{document}

结果

带开关:

\documentclass{article}

\newif\ifparboxheight
\newdimen\parboxheight

\makeatletter
\newcommand*{\org@iiiparbox}{}
\let\org@iiiparbox\@iiiparbox
\renewcommand*{\@iiiparbox}[2]{%
  \ifx\relax#2%
    \parboxheightfalse
    \setlength{\parboxheight}{0pt}%
  \else
    \parboxheighttrue
    \setlength{\parboxheight}{#2}%
  \fi
  \org@iiiparbox{#1}{#2}%
}
\makeatother


\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\newcommand*{\TestText}{%
  \raggedright
  Some text, some more text. The width is \the\linewidth
  \ifparboxheight
    \ and the height is \the\parboxheight
  \fi
  .%
}

\fbox{\parbox{100pt}{\TestText}}

\fbox{\parbox[][80pt][t]{100pt}{\TestText}}

\end{document}

切换结果

答案2

维度是#2的参数\@iiiparbox,因此我们可以进行修补\parbox以便将参数保存在长度寄存器中。

\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\newlength{\parboxtodim}
\patchcmd{\@iiiparbox}
  {\hsize}
  {\ifx\relax#2\else\setlength{\parboxtodim}{#2}\fi\hsize}
  {}{}
\makeatother

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

% here I'd like something like \parboxheight or similar
\fbox{\parbox[][200pt][t]{100pt}{%
  Some text, some more text, and \the\linewidth, and \the\parboxtodim
}}

\end{document}

在此处输入图片描述

答案3

\documentclass{standalone}
\newbox\mybox
\savebox\mybox{\parbox{100pt}{This is a test.}}
\begin{document}
\the\ht\mybox\ and \the\wd\mybox
\end{document}

在此处输入图片描述

相关内容