TIKZ 中的对角矩形

TIKZ 中的对角矩形

考虑以下 LaTeX 代码:

   \begin{tikzpicture}
        \node[circle,fill=red,text=white] (1) at (4,8)  {$R_1$};
        \node[circle,fill=red,text=white] (2) at (8,8)  {$R_1$};
        \node[circle,fill=blue,text=white] (4) at (4,5)  {$R_2$};
        \node[circle,fill=blue,text=white] (3) at (8,5)  {$R_2$};
        \draw[-] (1) -- node[above] {7} (2);
        \draw[-] (2) -- node[right] {7} (3);
        \draw[-] (3) -- node[below] {7} (4);
        \draw[-] (4) -- node[left] {7} (1);
        \draw[-] (1) -- node[pos=.2,below] {$10$} (3);
        \draw[-] (2) -- node[pos=.2,below] {$10$} (4);
        \node [draw=blue,  fit= (4) (3)] {};
        \node [draw=red, fit= (1) (2)] {};  

    \end{tikzpicture}

这为我们产生了这个形状:

这个图片

如何改变上述代码来制作如下所示的对角红色封闭矩形框?

这个图片

答案1

对角矩形适配

\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{fit}
\begin{document}
   \begin{tikzpicture}
        \node[circle,fill=red,text=white] (1) at (4,8)  {$R_1$};
        \node[circle,fill=red,text=white] (2) at (8,8)  {$R_1$};
        \node[circle,fill=blue,text=white] (4) at (4,5)  {$R_2$};
        \node[circle,fill=blue,text=white] (3) at (8,5)  {$R_2$};
        \draw[-] (1) -- node[above] {7} (2);
        \draw[-] (2) -- node[right] {7} (3);
        \draw[-] (3) -- node[below] {7} (4);
        \draw[-] (4) -- node[left] {7} (1);
        \draw[-] (1) -- node[pos=.2,below] {$10$} (3);
        \draw[-] (2) -- node[pos=.2,below] {$10$} (4);
        \node [draw=blue,  fit= (4) (3)] {};
        \node [draw=red, fit= (1) (2)] {};  
        \node [draw=orange, rotate fit=36, fit=(4)(2),  inner sep = 6pt] {};

    \end{tikzpicture}
\end{document}

您还可以在绘制注释之前计算线条的精确角度。

答案2

需要计算使用的角度rotate fit

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

\begin{document}

\newcommand{\nbox}[4][]{% \nbox[options]{node A}{node B}{fit node's name}
    \pgfmathanglebetweenpoints% calculates the angle of vector A to B
    {\pgfpointanchor{#2}{center}}{\pgfpointanchor{#3}{center}}
    \let\myresult\pgfmathresult
    \pgfmathparse{Mod(\myresult,90)}% for the anchors of the fit node to be consistent
    \let\myresult\pgfmathresult
    \node [draw=green, rotate fit=\myresult, fit = (#2) (#3), #1] (#4) {} ;
}


   \begin{tikzpicture}
        \node[circle,fill=red,text=white] (1) at (4,8)  {$R_1$};
        \node[circle,fill=red,text=white] (2) at (8,8)  {$R_1$};
        \node[circle,fill=blue,text=white] (4) at (4,5)  {$R_2$};
        \node[circle,fill=blue,text=white] (3) at (8,5)  {$R_2$};
        \draw[-] (1) -- node[above] {7} (2);
        \draw[-] (2) -- node[right] {7} (3);
        \draw[-] (3) -- node[below] {7} (4);
        \draw[-] (4) -- node[left] {7} (1);
        \draw[-] (1) -- node[pos=.2,below] {$10$} (3);
        \draw[-] (2) -- node[pos=.2,below] {$10$} (4);
        \node [draw=blue,  fit= (4) (3)] {};
        \node [draw=red, fit= (1) (2)] {};
        \nbox{2}{4}{5}
    \end{tikzpicture}

\end{document}

相关内容