10

The following MWE displays the desired output, but the question is whether (and how) the same result can be achieved by somehow redefining lines (1) and (2) to "cut out" the inner square, so that line (3) is redundant. I appreciate that this picture is simple, but one can easily imagine more complicated cases.

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\draw (-1,-1)--++(4,4);
\draw[fill=white] (0,0)--++(2,0)--++(0,2)--++(-2,0)--++(0,-2); % (1)
\draw (0.5,0.5)--++(1,0)--++(0,1)--++(-1,0)--++(0,-1); % (2)
\draw (0.5,0.5)--++(1,1); % (3)
\end{tikzpicture}

\end{document}
4
  • You can clip with the even odd rule (or the other one …). – Qrrbrbirlbel Jan 13 '13 at 15:10
  • @Qrrbrbirlbel What's evenoddrule ? I didn't see it in the pgfmanual. – Geoff Jan 13 '13 at 15:15
  • @Geoff: notice that the key is even odd rule with spaces; you can find it in 15.4.2 Graphic Parameters: Interior Rules at the end of the page. – Claudio Fiandrino Jan 13 '13 at 15:18
  • Ah! Those spaces help! – Geoff Jan 13 '13 at 15:21
11

Filling

If you actually want to fill the outer rectangle but not the inner, you can use the even odd rule (PGF manual, pp. 163f.)

Code

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}[even odd rule]
\draw (-1,-1) -- ++ (4,4);
\draw[fill=white] (0,0) rectangle ++ (2,2) (.5,.5) rectangle ++ (1,1);
\end{tikzpicture}
\end{document}

Output

enter image description here

Clipping

Another approach would be clipping, but as you want to “reverse-clip” the line to the boxes you will need a tweaked version of clip.

In this small example the following code suffices, but if you want to draw more or more sophisticated pictures you will need the reverseclip style from the referenced answer and/or a scope.

Reference

Code

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}[even odd rule]
\draw (0,0) rectangle (2,2) (1.5,1.5) rectangle (.5,.5);
\begin{pgfinterruptboundingbox}
\clip (0,0) rectangle (2,2) (1.5,1.5) rectangle (.5,.5) (3.1,3.1) rectangle (-1.1,-1.1);
\end{pgfinterruptboundingbox}
\draw (-1,-1)--++(4,4);
\end{tikzpicture}
\end{document}

Output

enter image description here

1
  • The "Filling" solution is what I was looking for. It keeps the code more logical (IMHO), in that we create the back line first, then the box with hole on top of that. Many thanks. – Geoff Jan 13 '13 at 15:34

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.