我想创建一个扁平六边形盒子的网格。盒子的每一边都是一个轻微的梯形(因此在 3D 中,边不会垂直于底部,但这对问题来说并不重要)。由于每条边都相同,只是位置不同,所以我尝试了以下 MWE。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\newcommand{\side}[1][10]{%
\begin{tikzpicture}
\coordinate (sO) at (0,0);
\path (sO)--++(-90:2) coordinate (sB);
\path (sO)--++({#1}:1) coordinate (sC);
\path (sB)--++({-1*#1}:1) coordinate (sD);
\draw (sO)--(sB)--(sD)--(sC)--(sO);
\end{tikzpicture}%
}
\begin{tikzpicture}
\coordinate (O) at (0,0);
\path (O)--++(0:2) coordinate (A1);
\path (O)--++(60:2) coordinate (A2);
\path (O)--++(120:2) coordinate (A3);
\path (O)--++(180:2) coordinate (A4);
\path (O)--++(240:2) coordinate (A5);
\path (O)--++(300:2) coordinate (A6);
\draw (A1)
--node[sloped,rotate=90,anchor=west]{\side}(A2)
--node[sloped,rotate=90,anchor=west]{\side}(A3)
--node[sloped,rotate=90,anchor=west]{\side}(A4)
--node[sloped,rotate=-90,anchor=west]{\side}(A5)
--node[sloped,rotate=-90,anchor=west]{\side}(A6)
--node[sloped,rotate=-90,anchor=west]{\side}(A1);
\end{tikzpicture}
\end{document}
六边形的边不齐平。有没有什么方法可以优雅地做到这一点?
或者也许我的代码可以改进,特别是拥有相同的节点信息(有时我需要rotate=90
,其他时候rotate=-90
)。
答案1
您需要修复节点inner sep=0pt
(或者更好的是 -\pgflinewidth)\side
。下一个代码显示了这两个选项。您还可以看到为什么梯形没有连接到六边形。每个节点的内容和节点边界之间都有一个(默认情况下不为零)inner sep
。
\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\begin{document}
\newcommand{\side}[1][10]{%
\begin{tikzpicture}
\coordinate (sO) at (0,0);
\path (sO)--++(-90:2) coordinate (sB);
\path (sO)--++({#1}:1) coordinate (sC);
\path (sB)--++({-1*#1}:1) coordinate (sD);
\draw (sO)--(sB)--(sD)--(sC)--(sO);
\end{tikzpicture}%
}
\begin{tikzpicture}
\coordinate (O) at (0,0);
\path (O)--++(0:2) coordinate (A1);
\path (O)--++(60:2) coordinate (A2);
\path (O)--++(120:2) coordinate (A3);
\path (O)--++(180:2) coordinate (A4);
\path (O)--++(240:2) coordinate (A5);
\path (O)--++(300:2) coordinate (A6);
\draw (A1)
--node[sloped,rotate=90,anchor=west, inner sep=-\pgflinewidth]{\side}(A2)
--node[sloped,rotate=90,anchor=west, inner sep=-\pgflinewidth]{\side}(A3)
--node[sloped,rotate=90,anchor=west, inner sep=0pt]{\side}(A4)
--node[sloped,rotate=-90,anchor=west, inner sep=-\pgflinewidth]{\side}(A5)
--node[sloped,rotate=-90,anchor=west, inner sep=0pt]{\side}(A6)
--node[sloped,rotate=-90,anchor=west, draw=red]{\side}(A1);
\end{tikzpicture}
\end{document}