计算包含节点和点的矩形

计算包含节点和点的矩形

我无法计算并绘制精确包含绿色矩形节点和红点(其精确坐标和尺寸可能有所不同)的框(即左下角和右上角)。

在此处输入图片描述

我试过这个代码,但它不起作用:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newdimen\XCoord
\newdimen\YCoord
\newcommand*{\ExtractCoordinate}[1]{\path (#1); \pgfgetlastxy{\XCoord}{\YCoord};}%

\begin{document}
\begin{tikzpicture}
  \clip (-2,-2) rectangle (10,8);

  \node[inner sep=2cm, fill=green] (rect) at (3,4) {Bla Bla};
  \node[inner sep=1pt, outer sep=0, circle, fill=red] (point) at (-1,1) {};

  \ExtractCoordinate{point.center}
  \edef\xone{\XCoord}
  \edef\yone{\YCoord}

  \ExtractCoordinate{rect.south west}
  \edef\xtwo{\XCoord}
  \edef\ytwo{\YCoord}
  \pgfmathparse{min(\xone,\xtwo)}
  \coordinate (x) at (\pgfmathresult,0);
  \pgfmathparse{min(\yone,\ytwo)}
  \coordinate (y) at (0,\pgfmathresult);

  \ExtractCoordinate{rect.north east}
  \edef\xtwo{\XCoord}
  \edef\ytwo{\YCoord}
  \pgfmathparse{max(\xone,\xtwo)}
  \coordinate (xx) at (\pgfmathresult,0);
  \pgfmathparse{max(\yone,\ytwo)}
  \coordinate (yy) at (0,\pgfmathresult);

  \draw ($(x) + (y)$) rectangle (0, 0);
  \draw ($(xx) + (yy)$) rectangle (1, 0);      
  \draw ($(x) + (y)$) rectangle ($(xx) + (yy)$);

  %% The expected result should be equivalent to drawing
  % \draw[orange, dashed] (\xone,\yone) rectangle (\xtwo, \ytwo);      
\end{tikzpicture}
\end{document}

我首先提取点的 X 和 Y 坐标以及矩形的西南和东北锚点,然后调用 min 和 max 函数。但是,我猜在这个阶段:\coordinate (x) at (\pgfmathresult,0);出了点问题,所以我得到了错误的值。

取消注释 tikzpicture 中的最后一行后即可看到预期结果。

答案1

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}

\begin{document}
\begin{tikzpicture}
  \clip (-2,-2) rectangle (10,8);

  \node[inner sep=2cm, fill=red] (rect) at (3,4) {};
  \node[inner sep=1pt, outer sep=0, circle, fill=red] (point) at (-1,1) {};

  \node[fit=(rect)(point), draw, thick, inner sep=0] {The tight
    encompassing rectangle}; %
  \node[fit=(rect)(point), draw, thick, inner sep=0.5cm, blue] {The
    encompassing rectangle with inner separation};
\end{tikzpicture}
\end{document}

结果是

包围矩形

相关内容