当我给出图片的高度并根据纵横比自动推导出图片的宽度时,如何将标题的宽度设置为与图片的宽度相同?
\begin{figure}
\includegraphics[height=10cm]{pic.png}
\caption{My very long caption ....}
\end{figure}
在这种情况下,图片位于左侧(假设宽度仅为 12 厘米),并且标题占据了整个文本宽度。
答案1
您需要将图像存储在保存框中,然后将标题包装到具有该框宽度的迷你页面中。
\documentclass{article}
\usepackage{graphicx}
\newsavebox\mysavebox
\usepackage{lipsum} % for example text only
\begin{document}
\lipsum
\begin{figure}
\centering
\sbox\mysavebox{\includegraphics[height=5cm]{example-image}}%
\usebox\mysavebox
\par
\begin{minipage}{\wd\mysavebox}
\caption{My very long long long long long long long long long long long long long long long long long long long caption }
\end{minipage}
\end{figure}
\lipsum
\end{document}
该adjustbox
包简化了这种方法,并且还避免了当图像大于通常的文本宽度时出现“坏框”警告。
\documentclass{article}
\usepackage{graphicx}
\usepackage{adjustbox}
\newlength\mylength
\usepackage{lipsum}
\begin{document}
\lipsum
\begin{figure}
\adjustimage{height=5cm, gstore width=\mylength, center}{example-image}
%alternative: \adjustbox{gstore width=\mylength,center}{\includegraphics[height=10cm]{example-image}}
\par% or empty line, needed to get caption below the image, not to the rigth
\adjustbox{minipage=\mylength,center}{\caption{My very long long long long long long long long long long long long long long long long long long long caption }}
\end{figure}
\lipsum
\end{document}
答案2
还有另外两种解决方案:使用measuredfigure
环境 fromthreeparttable
和\ffigbox
命令 from floatrow
;使用可选参数\ffigbox[\FBwidth]{image}{caption}
。 一个优点是,如果您希望标题仅比图形宽度宽一点,则只需更改[\FBwidth]
为[1.25\FBwidth]
:
\documentclass{article}
\usepackage{graphicx}
\usepackage{threeparttable, floatrow}
\newsavebox\mysavebox
\usepackage{lipsum} %
\begin{document}
%
\lipsum[2]
\begin{center}
\begin{measuredfigure} \centering
\includegraphics[height=5cm]{example-image}
\caption{My very long long long long long long long long long long long long long long long long long long long caption }
\end{measuredfigure}
\end{center}
\lipsum[3]
\begin{figure} \centering
\ffigbox[1.25\FBwidth]%
{\includegraphics[height=5cm]{example-image}}
{ \caption{My very long long long long long long long long long long long long long long long long long long long caption }}
\end{figure}
\end{document}