假设我有一个 4x4 矩阵,在 TikZ 中由 16 个节点表示。
我想绘制如下所示的对角矩形,我是否必须“手动”计算矩形每个顶部的坐标,还是可以更轻松地完成?
\documentclass{article}
\usepackage{amsmath, amsfonts, amssymb}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node (a) at (0, 0) {a};
\node (b) at (1,0) {b};
\node (c) at (2,0) {c};
\node (d) at (3,0) {d};
\node (e) at (0,-0.5) {e};
\node (f) at (1,-0.5) {f};
\node (g) at (2,-0.5) {g};
\node (h) at (3,-0.5) {h};
\node (i) at (0,-1) {i};
\node (j) at (1,-1) {j};
\node (k) at (2,-1) {k};
\node (l) at (3,-1) {l};
\node (m) at (0,-1.5) {m};
\node (n) at (1,-1.5) {n};
\node (o) at (2,-1.5) {o};
\node (p) at (3,-1.5) {p};
\end{tikzpicture}
\end{document}
答案1
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,calc}
\begin{document}
\begin{tikzpicture}
\matrix (M) [matrix of nodes]
{ a & b & c & d \\
e & f & g & h \\
i & j & k & l \\
m & n & o & p \\
};
\draw[blue,rounded corners]
let \p1=($(M-1-1)!-2mm!(M-4-4)$),
\p2=($(M-4-4)!-2mm!(M-1-1)$),
\p3=($(\p1)!2mm!90:(\p2)$),
\p4=($(\p1)!2mm!-90:(\p2)$),
\p5=($(\p2)!2mm!90:(\p1)$),
\p6=($(\p2)!2mm!-90:(\p1)$)
in
(\p3) -- (\p4)-- (\p5) -- (\p6) -- cycle;
\end{tikzpicture}
\end{document}
对于您稍晚来的 MWE:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node (a) at (0, 0) {a};
\node (b) at (1,0) {b};
\node (c) at (2,0) {c};
\node (d) at (3,0) {d};
\node (e) at (0,-0.5) {e};
\node (f) at (1,-0.5) {f};
\node (g) at (2,-0.5) {g};
\node (h) at (3,-0.5) {h};
\node (i) at (0,-1) {i};
\node (j) at (1,-1) {j};
\node (k) at (2,-1) {k};
\node (l) at (3,-1) {l};
\node (m) at (0,-1.5) {m};
\node (n) at (1,-1.5) {n};
\node (o) at (2,-1.5) {o};
\node (p) at (3,-1.5) {p};
\draw[blue,rounded corners]
let \p1=($(a)!-2mm!(p)$),
\p2=($(p)!-2mm!(a)$),
\p3=($(\p1)!2mm!90:(\p2)$),
\p4=($(\p1)!2mm!-90:(\p2)$),
\p5=($(\p2)!2mm!90:(\p1)$),
\p6=($(\p2)!2mm!-90:(\p1)$)
in
(\p3) -- (\p4)-- (\p5) -- (\p6) -- cycle;
\end{tikzpicture}
\end{document}
答案2
这个答案显示了如何让旋转的矩形适合任意两个给定的节点,因此不需要对您设置图片的方式进行任何改变。
\documentclass{article}
\usepackage{amsmath, amsfonts, amssymb}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\node (a) at (0, 0) {a};
\node (b) at (1,0) {b};
\node (c) at (2,0) {c};
\node (d) at (3,0) {d};
\node (e) at (0,-0.5) {e};
\node (f) at (1,-0.5) {f};
\node (g) at (2,-0.5) {g};
\node (h) at (3,-0.5) {h};
\node (i) at (0,-1) {i};
\node (j) at (1,-1) {j};
\node (k) at (2,-1) {k};
\node (l) at (3,-1) {l};
\node (m) at (0,-1.5) {m};
\node (n) at (1,-1.5) {n};
\node (o) at (2,-1.5) {o};
\node (p) at (3,-1.5) {p};
\pgfmathanglebetweenpoints{\pgfpointanchor{a}{center}}{\pgfpointanchor{p}{center}}
\pgfmathsetmacro{\myangle}{\pgfmathresult}
\node[draw=blue, rounded corners=2pt, rotate fit=\myangle, fit=(a) (p)] {};
\end{tikzpicture}
\end{document}
主要思想是使用fit
库,但需要添加旋转角度的计算。没有角度,fit
只会生成一个包含节点的矩形,但其边缘与坐标轴平行。