[Tex/LaTex] Setting width of figure element in fbox / minipage

captionsfboxminipage

Following code is currently used to show a figure:

\begin{figure}[ht]
  \lineskip=-\fboxrule
  \fbox{\begin{minipage}{\dimexpr\textwidth-2\fboxsep-2\fboxrule}
    \centering
    \includegraphics[width=0.5\textwidth]{example-image}
  \end{minipage}}
  \fbox{\begin{minipage}{\dimexpr\textwidth-2\fboxsep-2\fboxrule}
    \caption{The caption text}
  \end{minipage}}
  \label{fig:test}
\end{figure}

Image with caption

Question: How can I adjust the code so that the full box is only 0.5\textwidth of a page, with the image being full width within the box?

Best Answer

\documentclass{article}
\usepackage[export]{adjustbox}

\begin{document}
\begin{figure}[ht]
\lineskip=-\fboxrule
\fbox{\parbox{0.5\linewidth}{\includegraphics[width=\linewidth]{example-image}}}\\ \fbox{\parbox{0.5\linewidth}{
    \caption{The caption text}
    \label{fig:test}
                        }}
\end{figure}
\end{document}

enter image description here

addedndum: if you have many such figures, than it might be sensible to define new command as:

\newcommand\fparbox[2]{\fbox{\parbox{#1}{#2}}}

and than use it as follows:

\documentclass{article}
\usepackage[export]{adjustbox}
\newcommand\fparbox[2]{\fbox{\parbox{#1}{#2}}}

\begin{document}
\begin{figure}[ht]
\lineskip=-\fboxrule
\fparbox{0.5\linewidth}{\includegraphics[width=\linewidth]{example-image}}\\    
\fparbox{0.5\linewidth}{
    \caption{The caption text}
    \label{fig:test}
                        }
\end{figure}
\end{document}

result is the same as before.

Related Question