[Tex/LaTex] Box around caption in figure

captionsframed

I am wondering if it is possible, in a figure, to put a box around just the caption and not the whole figure.

\documentclass[12pt,letter]{article}    
\usepackage[demo]{graphicx}     

\begin{document}

\begin{figure}
\includegraphics[width=6in]{foo.ps}

\caption{I sure hope I can be boxed separate from the picture...}
%some command that can put a box around the caption
\end{figure}

\end{document}

EDIT I added the [width=6in] on the \includegraphics command. It is a necessary part of the figures I'm including.

Best Answer

The following adjustment to \@makecaption places the figure caption inside a box that adjusts to the width of the caption:

enter image description here

\documentclass{article}
\usepackage{graphicx}% http://ctan.org/pkg/graphicx

\makeatletter
\long\def\@makecaption#1#2{%
  \vskip\abovecaptionskip
  \sbox\@tempboxa{\fbox{#1: #2}}%
  \ifdim \wd\@tempboxa >\hsize
    \fbox{\parbox{\dimexpr\linewidth-2\fboxsep-2\fboxrule}{#1: #2}}\par
  \else
    \global \@minipagefalse
    \hb@xt@\hsize{\hfil\box\@tempboxa\hfil}%
  \fi
  \vskip\belowcaptionskip}
\makeatother

\begin{document}

\begin{figure}
  \centering
  \includegraphics[width=100pt]{example-image}
  \caption{I sure hope I can be boxed separate from the picture\ldots}
  \caption{I sure hope I can be boxed separate from the picture.
   I sure hope I can be boxed separate from the picture.
   I sure hope I can be boxed separate from the picture.}
\end{figure}

\end{document}

The definition of \@makecaption was taken (and changed) from article.cls.


caption also allows for setting a caption style. So, if you're interested in a fixed-width caption, you can use something similar to the following:

enter image description here

\documentclass{article}
\usepackage{caption,graphicx}% http://ctan.org/pkg/{caption,graphicx}

\DeclareCaptionFormat{plain}{%
  \fbox{\parbox{\dimexpr\linewidth-2\fboxsep-2\fboxrule}{\centering #1#2#3}}}

\begin{document}

\begin{figure}
  \centering
  \includegraphics[width=100pt]{example-image}
  \caption{I sure hope I can be boxed separate from the picture\ldots}
  \caption{I sure hope I can be boxed separate from the picture.
   I sure hope I can be boxed separate from the picture.
   I sure hope I can be boxed separate from the picture.}
\end{figure}

\end{document}

The style is set to \centering #1#2#3 where #1 refers to the caption label, #2 the caption label separator and #3 the caption text. See section 4 Own enhancements (p 24) of the caption package documentation.