在 LaTeX 中,创建一个与另一个文本宽度相同的框

在 LaTeX 中,创建一个与另一个文本宽度相同的框

我正在寻找一个类似的命令,它可以使一个包含居中\makebox{text to set width}[c]{new text}的宽度的框成为可能。text to set width____new text____

答案1

像这样吗?

\documentclass{article}
\newlength\stextwidth
\newcommand\makesamewidth[3][c]{%
  \settowidth{\stextwidth}{#2}%
  \makebox[\stextwidth][#1]{#3}%
}
\begin{document}
  \fbox{\makesamewidth[c]{text to set width}{new text}}
\end{document}

匹配宽度

如果参数的顺序很重要,您可以使用xparse

\documentclass{article}
\usepackage{xparse}
\newlength\stextwidth
\NewDocumentCommand\makesamewidth{ m O{c} m }{%
  \settowidth{\stextwidth}{#1}%
  \makebox[\stextwidth][#2]{#3}%
}
\begin{document}
  \fbox{\makesamewidth{text to set width}[c]{new text}}
\end{document}

使用\NewDocumentCommand而不是\newcommand

答案2

calc提供\widthof{<stuff>}

在此处输入图片描述

\documentclass{article}
\usepackage{calc}
\setlength{\parindent}{0pt}% Just for this example
\begin{document}
Here is some text that is lengthy.\par
\makebox[\widthof{Here is some text that is lengthy}][l]{Left}\par
\makebox[\widthof{Here is some text that is lengthy}][c]{Centre}\par
\makebox[\widthof{Here is some text that is lengthy}][r]{Right}\par
\makebox[\widthof{Here is some text that is lengthy}][s]{S p a c e d}
\end{document}

还有另一种尴尬的方式来实现你的目标tabular

在此处输入图片描述

\documentclass{article}
\setlength{\parindent}{0pt}% Just for this example
\makeatletter
\newcommand{\widthbox}[1]{\gdef\stext{#1}\widthbox@}
\newcommand{\widthbox@}[2][c]{%
  \begin{tabular}{@{}#1@{}}
    \phantom{\stext} \\[-\normalbaselineskip]
    #2
  \end{tabular}}
\begin{document}
Here is some text that is lengthy.\par
\widthbox{Here is some text that is lengthy}[l]{Left}\par
\widthbox{Here is some text that is lengthy}[c]{Centre}\par
\widthbox{Here is some text that is lengthy}[r]{Right}
\end{document}

答案3

定义新的长度\mylen,然后将其设置为文本的宽度。

\documentclass{article}
\newlength{\mylen}
\settowidth{\mylen}{text to set width}
\begin{document}
  text to set width

  \makebox[\mylen][c]{new text}
\end{document}

在此处输入图片描述

答案4

最简单的方法可能是使用eqparbox包:它定义的\eqparbox, eqmakebox, \eqframebox, \eqsavebox命令具有与基本 LaTeX 对应命令相同的参数,只是宽度参数被替换为标签。所有具有相同标签的框的宽度都与其中最宽的框相同。此外,还有一个\eqboxwidth{tag}长度,可用作长度参数。

对于简单的需求,小包makebox定义了一个\makebox*{longer reference text}{shorter text}命令。

    \documentclass[12pt]{article}
    \usepackage[utf8]{inputenc}
    \usepackage{lipsum}
    \usepackage{makebox}
    \usepackage{eqparbox}
    \setlength\fboxsep{12pt}

    \begin{document}

     \begin{tabular}{c}
            \fbox{\makebox*{Blahblahblah, blahblahblah, blahblahblah…}{Blahblahblahblah}}\\\\
            \fbox{\eqparbox{boxa}{Blahblahblah, blahblahblah, blahblahblah…}}\\\\
            \eqframebox[boxa]{Blahblahblahblah}\\\\
            \eqframebox[boxa]{Blahblahblah, blahblahblah, blahblahblah…}\\\\
            \fbox{\parbox{\eqboxwidth{boxa}}{\lipsum[2]}}
     \end{tabular}

    \end{document} 

在此处输入图片描述

相关内容