[Tex/LaTex] putting a box over an image in beamer presentation

beamergraphicstikz-pgf

In a Beamer presentation, I want to put a box over a graphic file. For example, in one slide, I want to put a graphic file:
first slide

And, in the next slide, I want to put a box on the image:
second slide

This style of work was what I usually do with MS Powerpoint. I was wondering how I can do this with Beamer. If there is any other elegant way to do this with the similar purpose (i.e. pointing and emphasizing a part of images), I am open to any suggestion as well.

Best Answer

How about this: you have three commands:

  • \imagenode for inserting the picture and setting up some dimensions
  • the optional \imagegrid which helps putting the frame
  • \highlightbox for drawing the frame

Code

\documentclass{beamer}
\usepackage{tikz}

\newcommand{\imagenode}[2][1]% [scale], filename
{   \node[above right,inner sep=0] (myimage) {\includegraphics[scale=#1]{#2}};
    \path (myimage.north east);
    \pgfgetlastxy{\myimagex}{\myimagey}
    \pgfmathsetmacro{\myimagewidth}{\myimagex/28.453}
    \pgfmathsetmacro{\myimageheight}{\myimagey/28.453}
}

\newcommand{\imagegrid}[4][help lines]% [options], steps, font, precision
{   \pgfkeys{/pgf/number format/.cd,fixed,precision=#4}
    \foreach \x in {0,...,#2}
    {   \draw[#1] (\x/#2*\myimagewidth,\myimageheight) -- (\x/#2*\myimagewidth,0) node[below] {#3\pgfmathparse{\x/#2}\pgfmathprintnumber{\pgfmathresult}};
        \draw[#1] (\myimagewidth,\x/#2*\myimageheight) -- (0,\x/#2*\myimageheight) node[left] {#3\pgfmathparse{\x/#2}\pgfmathprintnumber{\pgfmathresult}};
    }
}

\newcommand{\highlightbox}[8][densely dashed,thick]% [options], left, low, right, up, node options, node text, overlay spec
{   \only<#8>{\draw[#1] (#2*\myimagewidth, #3*\myimageheight) rectangle node[#6] {#7} (#4*\myimagewidth, #5*\myimageheight);}
}

\begin{document}

\begin{frame}
    \begin{tikzpicture}
        \imagenode[3]{book.png}

        \imagegrid{10}{\tiny}{1}

        \highlightbox[red,very thick]{0.1}{0.1}{0.7}{0.2}{blue}{red frame}{2}
        \highlightbox{0}{0.3}{0.3}{0.7}{circle,draw,fill=green!50!gray,solid}{dash}{2-3}
        \highlightbox[blue,fill=blue,fill opacity=0.3]{0.42}{0.23}{0.65}{0.74}{opacity=0.8,fill=orange,text opacity=1}{!?}{1,3}
    \end{tikzpicture}
\end{frame} 

\end{document}

Output

enter image description here