12

I often have AVMs/tables that are just a bit too large and use \resizebox to fit everything in one line. Now, if the linewidth changes (switch from twocolumn to onecolumn) this results in enlarging the text.

\newcommand{\oneline}[1]{\resizebox{\linewidth}{!}{#1}}

Is there some way to reach the same result but without the possibility of enlarging the box?

3 Answers 3

8

The following example puts the contents in a box (this is done by \resizebox anyway), measures the width and applies \resizebox if necessary:

\documentclass{article}
\usepackage{graphicx}

\newcommand*{\restrictlinewidthbox}[1]{%
  \begingroup
    \sbox0{#1}%
    \ifdim\wd0>\linewidth
      \resizebox{\linewidth}{!}{\copy0}%
    \else
      \copy0 %
    \fi
  \endgroup
}

\setlength{\parindent}{0pt}

\begin{document}

\restrictlinewidthbox{\rule{10mm}{10mm}}

\restrictlinewidthbox{\rule{2\linewidth}{10mm}}

\end{document}

Result

David Carlisle's trick

\resizebox{\ifdim\width>\linewidth\linewidth\else\width\fi}{!}{\rule{10mm}{10mm}}

also applies the resizing, if the natural \width is used. For example, the result in this case with pdflatex is a scaling factor of 1.00005 instead of 1.

Rounding errors of \resizebox

The calculations of \resizebox are not too precise. Especially the box can be a little larger than specified. The following variant contributes the rounding error to the left and right of the box:

\newcommand{\restrictlinewidthbox}[1]{%
  \begingroup
    \sbox0{\ignorespaces#1\unskip}%
    \leavevmode
    \ifdim\wd0>\linewidth
      \hbox to\linewidth{%
        \hss\resizebox{\linewidth}{!}{\copy0 }\hss
      }%
    \else
      \copy0 %
    \fi
  \endgroup
}

See question "Vertical space in interaction with figure/center environment" and my answer there.

5
\resizebox{\ifdim\width>\linewidth\linewidth\else\width\fi}{!}{#1}}

probably works

5

Use adjustbox:

\documentclass{article}
\usepackage{graphicx,adjustbox}

\newcommand*{\restrictlinewidthbox}[1]{%
  \adjustbox{max width=\linewidth}{#1}%
}

\setlength{\parindent}{0pt}

\begin{document}

\restrictlinewidthbox{\rule{10mm}{10mm}}

\restrictlinewidthbox{\rule{2\linewidth}{10mm}}

\end{document}

(For the picture, I added the frame lines with geometry, not shown in the source.)

enter image description here

You can, of course, use \adjustbox directly or in its environment form:

\begin{adjustbox}{max width=\linewidth}
<material>
\end{adjustbox}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.