1

Consider this application:

\documentclass[border=5pt]{standalone}
\usepackage{graphicx}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \node(a) at (0.0, 0.0)[anchor=south west]{\includegraphics[width=0.3\paperwidth]{example-image-a}};
  \draw[blue, fill=red] (0.15\paperwidth, 0.0\paperwidth) rectangle (0.3\paperwidth, 0.15\paperwidth);
\end{tikzpicture}
\end{document}

enter image description here

My goal is to draw a rectangle over the right half of the example image. I am guessing the rectangle coordinates knowing that the width is width=0.3\paperwidth and approximately the aspect ratio.

I would like to be very precise. How can I draw the rectangle over exactly the half of example image a? Such as knowing the height and width of node a.

1

Rectangle more exactly cover image with the correcting outer sep Of image node:

\documentclass[border=5pt]{standalone}

\usepackage{graphicx}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
\node (a) [inner sep=0pt, 
           outer sep=-0.5\pgflinewidth] % <---
{\includegraphics[width=0.3\paperwidth]{example-image-a}};
        \draw[blue, fill=red, semitransparent] (a.south) rectangle (a.north east);
    \end{tikzpicture}
\end{document}

enter image description here

or by use of fit library:

\documentclass[border=5pt]{standalone}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{fit}

\begin{document}
    \begin{tikzpicture}
\node (a) [inner sep=0pt, 
           outer sep=-0.5\pgflinewidth] % <---
{\includegraphics[width=0.3\paperwidth]{example-image-a}};
\node [draw=blue, fill=red, semitransparent, inner sep=0pt,
       fit=(a.south)(a.north east)] {};
    \end{tikzpicture}
\end{document}

The result s the same as before.

1

You can use the nodes positions to position the red square precisely above the picture.

v02

\documentclass[border=5pt]{standalone}

\usepackage{graphicx}
\usepackage{tikz}

\usetikzlibrary{calc}

\begin{document}
    \begin{tikzpicture}
        \node(a) at (0,0)[inner sep=0pt, outer sep=0pt,anchor=south west] {\includegraphics[width=0.3\paperwidth,keepaspectratio]{example-image-a}};
        \draw[blue, fill=red, opacity=0.5] (a.south) rectangle (a.north east);
    \end{tikzpicture}
\end{document}
2
  • if you do width=0.3\paperwidth, height=0.3\paperwidth you most likely distort the aspect ratio in the real life image.
    – Viesturs
    May 10 at 8:38
  • @Viesturs You are right. I changed the answer accordingly.
    – Excelsior
    May 10 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.