[Tex/LaTex] Annotating picture with tikz and positioning

tikz-pgf

I am annotating a picture with tikz.

I have tried

\documentclass[tikz]{standalone}

\usetikzlibrary{shapes,arrows,positioning,decorations.pathreplacing}

\begin{document}

\tikzset{%
    box/.style = {red, thick, rounded corners},
    arrow/.style = {->, green, ultra thick},
}

\begin{tikzpicture}[node distance=0.1cm, auto]
    % image
    \node[anchor=south west,inner sep=0] (image) at (0,0) {%
        \includegraphics[width=0.9\textwidth]{img/navbar.PNG}
    };

    % annotate
    \begin{scope}[x={(image.south east)},y={(image.north west)}]
        \draw[box] (0.02,0.15) rectangle (0.1,0.9);
        \node at (-0.02,-1) {Home};
        \draw[arrow] (0,-0.8) -- (0.02,0.15);
    \end{scope}
\end{tikzpicture}

\end{document}

My code works but I have manually placed my node with text "Home". I have to draw multiple boxes with text to each box. I also want an arrow from the text to the box to which the text belongs.

Can I use some positioning magic? I have tried naming the drawn rectangle with \draw[box] (home) (0.02,0.15) rectangle (0.1,0.9); but it's apparently not allowed to name rectangles like I can name nodes.

Best Answer

You can add a coordinate at one corner of the rectangle, draw a line with the end point relative to this with the ++(x,y) syntax, and add the Home node at the end of the line. Adjust the value for shorten < to your liking.

enter image description here

\documentclass[tikz,border=3mm]{standalone}

\usetikzlibrary{shapes,arrows,positioning,decorations.pathreplacing}

\begin{document}

\tikzset{%
    box/.style = {red, thick, rounded corners},
    arrow/.style = {->, green, ultra thick},
}

\begin{tikzpicture}[node distance=0.1cm, auto]
    % image
    \node[anchor=south west,inner sep=0] (image) at (0,0) {%
        \includegraphics[width=0.9\textwidth]{example-image}
    };

    % annotate
    \begin{scope}[x={(image.south east)},y={(image.north west)}]
        \draw[box] (0.02,0.15) coordinate(box1) rectangle (0.1,0.9);
        \draw [arrow,shorten <=1pt] (box1) -- ++(-0.1,-0.7) node[below,black]{Home};
    \end{scope}
\end{tikzpicture}

\end{document}