我的目标: 我需要打印文本的准确长度
默认宽度345 pt
如你所见。
但如果我计算
"some text .... some"
我得到的347.069 pt
文本宽度
如果我计算"some text .... someE"
我得到352.039 pt
这不应该发生,因为两个文本都是一行,因此最大应该是 345 pt。我该如何解决这个问题?谢谢!
\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[sfdefault,condensed,light]{roboto}
\usepackage[utf8]{inputenc}
\setlength{\parindent}{0pt} % = global \noindent
\begin{document}
The text width is: \the\textwidth
some text some text some text some text some text some text some text some text some
\newlength{\myl}
\settowidth{\myl}{some text some text some text some text some text some text some text some text some}
\the\myl
some text some text some text some text some text some text some text some text someE
\newlength{\myle}
\settowidth{\myle}{some text some text some text some text some text some text some text some text someE}
\the\myle
\end{document}
答案1
tabto
来帮忙。它可以测量“就地”的水平文本位置。因此,可以在两个位置进行测量并减去差值。但要小心!!如果被测量的文本换行,那么它可能会生成一个负数,因为文本的最终位置可能位于初始位置的左侧。
在这种情况下,如果原作者可以进一步限制问题,也许可以采取一些措施……例如,测量文本的总宽度必须小于\linewidth
,但如果测量从中间开始,则允许单行换行。这就是我下面所做的。
\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[sfdefault,condensed,light]{roboto}
\usepackage[utf8]{inputenc}
\setlength{\parindent}{0pt} % = global \noindent
\usepackage{tabto}
\makeatletter
\newcommand\settoactualwidth[2]{%
\tabto*{0pt}%
\@tempdima=\TabPrevPos\relax
\tabto{\TabPrevPos}
#2%
\tabto*{0pt}%
\ifdim\TabPrevPos>\@tempdima\relax
#1=\dimexpr\TabPrevPos-\@tempdima\relax
\else
#1=\dimexpr\TabPrevPos-\@tempdima + \linewidth\relax
\fi
\tabto{\TabPrevPos}}
\makeatother
\begin{document}
The text width is: \the\textwidth
some text some text some text some text some text some text some text some text some
\newlength{\myl}
\settoactualwidth{\myl}{some text some text some text some text some text some text some text some text some}
\the\myl
some text some text some text some text some text some text some text some text someE
\newlength{\myle}
\settoactualwidth{\myle}{some text some text some text some text some text some text some text some text someE}
\the\myle
\hspace{.8in}\settoactualwidth{\myl}{some text some text some text some text some text some text some text some}
\the\myl
\end{document}
答案2
\measurew{text}
我建议使用测量宽度的宏并将结果设置到text
寄存器中。\vbox
\tmpdim
该宏\try
仅显示效果,即它在测量的文本下方绘制具有宽度的规则\tmpdim
并打印的值\tmpdim
。
\newdimen\tmpdim
\def\measurew#1{\setbox0=\vbox{#1\par
\setbox0=\lastbox \global\setbox0=\hbox{\unhbox0}
\global\tmpdim=\ifdim\wd0>\hsize \hsize \else \wd0 \fi
\unskip\unskip\unpenalty \setbox0=\lastbox
\ifvoid0 \else \global\tmpdim=\hsize \fi
}}
\def\try#1{#1\medskip\measurew{#1}\hrule width\the\tmpdim
\medskip \hbox{\the\tmpdim}\bigskip}
\hsize=8cm
\noindent hsize=\the\hsize
\medskip
\try{Text.}
\try{Long long text.}
\try{Long long text. Long long text. Long long text.}
\try{Long long text. Long long text. Long long texttt.}
\try{Long long text. Long long text. Long long long text.}
\bye