4

Minimal example, multiplying by 0.5 makes the command fail :

\documentclass{beamer}
\usepackage{graphicx}
\begin{document}
\newcommand{\dontwork}[1]{\includegraphics[width=0.5*(#1)\textwidth]{frog.jpg}}
\newcommand{\work}[1]{\includegraphics[width=#1\textwidth]{frog.jpg}}

\begin{frame}{Frame 1}
    \dontwork{1}
\end{frame}
\end{document}

I get this error : Here is my error

0

3 Answers 3

4

Use \dimexpr (provided by the e-TeX extensions whose availability is standard in LaTeX nowadays):

\includegraphics[width=\dimexpr.5\textwidth*(#1)\relax]{frog.jpg}

Be aware that in case of multiplication the formal syntax of \dimexpr requires the dimension to come first and the scaling-factor to come last, nested in parentheses in case it is formed by a numerical expression. E.g.,
\dimexpr(.5\textwidth)*(#1)\relax
does work if #1 forms a valid numerical expression while
\dimexpr(#1)*(.5\textwidth)\relax
does not.

If #1 shall not necessarily be an integer, then scale the \dimexpr itself:

\includegraphics[width=#1\dimexpr.5\textwidth\relax]{frog.jpg}
or
\includegraphics[width=.5\dimexpr#1\textwidth\relax]{frog.jpg}

3

You could use

  \includegraphics[width=#1\dimexpr0.5\textwidth\relax]{...}

Alhough specifying a fraction of half \textwidth seems a very weird interface, are you wanting a fraction of \columnwidth ??

4
  • In my use case I multiply by 0.77 to suit the beamer height
    – Butanium
    May 23 at 10:05
  • @Butanium still seems strange to me, why not scale by height rather than width if height is the limiting dimension? May 23 at 10:07
  • it'll be easier to give you my use case directly : \newcommand{\adaptgraphics}[2][1]{\includegraphics[width=#1\textwidth,height=#1\dimexpr0.77\textheight,keepaspectratio]{figures/#2}}
    – Butanium
    May 23 at 10:12
  • @Butanium OK:-) May 23 at 10:14
0

I got an answer on a latex discord :

\newcommand{\flatfrog}[1]{\includegraphics[width=\dimexpr 0.33\textwidth*(#1)\relax]{frog.jpg}}

Works, \dimexpr makes the evaluation preserving the dimension of \textwidth which is needed

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.