需要 TeX 專家:如何設定(最佳)寬度?

需要 TeX 專家:如何設定(最佳)寬度?

有一個問題我已經嘗試解決一段時間了,但到目前為止還沒有成功。據我所知,TeX 非常擅長根據固定的容器寬度適當地中斷文字行。我想要實現的目標是不同的:我希望能夠計算給定內容的「最佳」寬度。

我所說的最優是指存在一個潛在的限制。例如,我希望能夠寫一個命令\settooptimalwidth#1#2#3

  • #1 作為長度來調整
  • #2 作為最大寬度
  • #3 作為內容

如果 #3 非常短(比 #2 短),它會簡單地執行與 相同的操作\settowidth。如果 #3 比 #2 長,它會將 #3 分成幾行,就像將其放入迷你盒中一樣,並且(這是棘手的部分)返回其中最寬的行的長度。我在這裡假設換行演算法不使用通常的“合理”對齊,而是使用左/右對齊或居中(否則問題是無關緊要的)。

讓我舉幾個例子,這樣的命令會很有用: * 自動調整其內容居中的數組列的寬度,可能會斷行, * 某種帶有精美框架的右對齊詩句環境。如果詩句很短,那麼框架就會很小。如果這節經文很長,它會將文字分成「最佳」寬度。

我認為要走的路是 with \unhbox,但我不確定如何使用它。任何幫助,將不勝感激。

答案1

正如大衛·卡萊爾(David Carlisle)上面所寫,打包varwidth是最佳選擇。它提供了varwidth滿足我要求的環境。這是一個使用投影機在漸變陰影背景上繪製文字的最小範例。

\documentclass{beamer}

\usepackage{calc,varwidth}

\colorlet{titleshadeA}{white!30!orange}
\colorlet{titleshadeB}{red!30!black}

\newlength\shadeboxwidth
\newlength\shadeboxheight
\newlength\shadeboxsep
\newcommand\shadebox[4]{%
  \setlength\shadeboxsep{#3}%
  \settowidth\shadeboxwidth{\begin{varwidth}{\textwidth}#4\end{varwidth}}%
  \advance\shadeboxwidth by 2\shadeboxsep%
  \settototalheight\shadeboxheight{\begin{varwidth}{\textwidth}#4\end{varwidth}}%
  \advance\shadeboxheight by 2\shadeboxsep%
  \pgfdeclarehorizontalshading{titleshade}{\shadeboxheight}{%
    color(0mm)=(#1);%
    color(\shadeboxwidth)=(#2)%
  }%
  \rlap{\pgfuseshading{titleshade}}%
  \begin{beamercolorbox}[sep=\shadeboxsep,wd=\shadeboxwidth,ht=\shadeboxheight,dp=0pt]{postit}%
    \color{white}\begin{varwidth}{\textwidth}\raggedleft#4\end{varwidth}%
  \end{beamercolorbox}%
}

\begin{document}
\begin{frame}
\strut\hfill\shadebox{titleshadeA}{titleshadeB}{1ex}{\raggedleft\LARGE Something short}\\
\strut\hfill\shadebox{titleshadeA}{titleshadeB}{1ex}{\raggedleft\LARGE Something very long which will be broken and aligned to the right}\bigskip
\hrule height 2pt\bigskip
Notice how it doesnt spawn the total text width (see the black rule above), but instead adjusts itself to the longest text line of the content.
\end{frame}
\end{document}

相關內容