如何强制两个 \includegraphics 使用相同的调整大小因子?

如何强制两个 \includegraphics 使用相同的调整大小因子?

我有两幅图像,我想将它们并排放置为子图(带有不同的标题)。图像大小不同,但它们具有必须保持大小相等的元素(例如文本)。我希望图形的总宽度为\textwidth,并调整两幅图像的大小同样的因素来实现这一点。但是,据我所知,尺寸是单独设置的\includegraphics...我该怎么办?

答案1

可以计算图像的比例因子:

\documentclass[a5paper]{article}
\usepackage{graphicx}

% Space between images
\newdimen\imgsep
\setlength{\imgsep}{1em}


\begin{document}

\makeatletter
\sbox0{\includegraphics[page=1]{img}}
\sbox2{\includegraphics[page=2]{img}}
\edef\ImgScaleFactor{%
   \strip@pt
   \dimexpr 1pt
     * \number\dimexpr \linewidth - \imgsep \relax
     / \number\dimexpr \wd0 + \wd2 \relax
   \relax
   % Uses the higher precision of eTeX's scaled operation
   % (multiplication followed by division)
}
\typeout{Image scale factor: \ImgScaleFactor}
\makeatother

\hrule % shows text/line width
\vspace{1ex}

\noindent
\includegraphics[scale=\ImgScaleFactor, page=1]{img}\hfill
\includegraphics[scale=\ImgScaleFactor, page=2]{img}

\vspace{1ex}
\hrule

\end{document}

结果

该两页图像文件由以下来源img.pdf生成:pdflatex

\documentclass{article}
\usepackage{xcolor}
\pagecolor{black!15!white}
\setlength{\pdfhorigin}{0pt}
\setlength{\pdfvorigin}{0pt}
\setlength{\fboxrule}{0pt}
\begin{document}
\newcommand*{\x}[1]{%
  \sbox0{\fbox{#1}}%
  \setlength{\pdfpagewidth}{\wd0}%
  \setlength{\pdfpageheight}{\dimexpr\ht0+\dp0\relax}%
  \shipout\copy0 %
}
\x{First image}
\x{Second graphics}
\end{document}

答案2

以下是主要基于 Werner 的回答的解决方案存储并重现有效的图形缩放

我们使用 fp 库进行计算,将图像的宽度存储在临时变量中。

示例输出

\documentclass{article}

\usepackage{xparse,graphicx,etoolbox,caption,floatrow}

\ExplSyntaxOn
  \cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff

\makeatletter
\newcommand{\scalefactor}[3]{% image1, image2, marco-name-for-result
  \settowidth{\@tempdima}{\includegraphics{#1}}%
  \settowidth{\@tempdimb}{\includegraphics{#2}}%
  \setlength{\@tempdima}{\dimexpr\@tempdima+\@tempdimb+2em\relax}
  \csedef{#3}{\calc{\strip@pt\textwidth/\strip@pt\@tempdima}}
}
\makeatother

\begin{document}

% The next two lines print the original images for demonstration purposes
% and so should be omitted in final code

\includegraphics{example-image-1x1}

\includegraphics{example-image-16x10}

% Here we compute the scale factor, display it (again just for 
% demonstration purposes) and then use the resulting 
% value to produce the correctly scaled images

\scalefactor{example-image-1x1}{example-image-16x10}{figscale}

Calculated figure scale: \figscale

\begin{figure}
  \begin{floatrow}
    \ffigbox[\FBwidth]{\caption{First figrue}\label{fig:1}}%
    {\includegraphics[scale=\figscale]{example-image-1x1}}
    \ffigbox[\FBwidth]{\caption{Second figure}\label{fig:2}}%
    {\includegraphics[scale=\figscale]{example-image-16x10}}
  \end{floatrow}
\end{figure}

\end{document}

相关内容