有没有一种简单的方法可以在 TikZ 中绘制三角形网格,像这样?
答案1
就像 Leo 所说的那样:使用\foreach
一些数学知识:
\usetikzlibrary{calc}
\newcommand*\rows{10}
\begin{tikzpicture}
\foreach \row in {0, 1, ...,\rows} {
\draw ($\row*(0.5, {0.5*sqrt(3)})$) -- ($(\rows,0)+\row*(-0.5, {0.5*sqrt(3)})$);
\draw ($\row*(1, 0)$) -- ($(\rows/2,{\rows/2*sqrt(3)})+\row*(0.5,{-0.5*sqrt(3)})$);
\draw ($\row*(1, 0)$) -- ($(0,0)+\row*(0.5,{0.5*sqrt(3)})$);
}
\end{tikzpicture}
答案2
A有趣的解决方案(你曾经使用过吗lindenmayersystems
图书馆?):
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{lindenmayersystems}
\begin{document}
\begin{tikzpicture}
\pgfdeclarelindenmayersystem{triangular grid}{\rule{F->F-F+++F--F}}
\path[draw=black,
l-system={triangular grid,step=1cm,
angle=-60,axiom=F--F--F,order=4,
}]
lindenmayer system -- cycle;
\end{tikzpicture}
\end{document}
答案3
使用矩阵变换和剪辑的稍微不同的解决方案:
\newcommand*{\rows}{10}
\pgfmathsetmacro{\xcoord}{cos(60)}
\pgfmathsetmacro{\ycoord}{sin(60)}
\begin{tikzpicture}
\pgftransformcm{1}{0}{\xcoord}{\ycoord}{\pgfpointorigin}
\path[clip,preaction = {draw=black}] (\rows,0) -- (0,0) -- (0,\rows) -- cycle;
\draw (0,0) grid (\rows,\rows);
\foreach \x in {1,2,...,\rows} {
\draw (0,\x) -- (\x,0);
}
\end{tikzpicture}
答案4
接下来的代码定义了绘制\grid
由三角形节点组成的三角形网格的命令。\grid
的参数是行数。minimum size
是tri/.style
三角形外接圆的直径。
使用节点而不是线条,可以更容易地使用网格作为漂亮TiKZ
绘图的基础。
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{shapes}
\newcommand{\grid}[1]{
\foreach \i [count=\row from 0, remember=\row as \lastrow (initially 0)] in {0,...,#1}{
\foreach \j [count=\column from 0, remember=\column as \lastcolumn (initially 0)] in {0,...,\i}{
\ifnum\row=0
\node[tri](0-0){0-0};
\else
\ifnum\column=0
\node[tri, anchor=north](\row-0) at (\lastrow-0.corner 2) {\row-0};
\else
\node[tri, anchor=north](\row-\column) at (\lastrow-\lastcolumn.corner 3) {\row-\column};
\fi
\fi}}
}
\begin{document}
\begin{tikzpicture}[tri/.style={draw=gray, regular polygon, regular polygon sides=3,
minimum size=2cm, inner sep=0pt, outer sep=0pt}]
\grid{5}
\begin{scope}[draw=yellow!30!black, very thick, fill=yellow!80!black]
\filldraw[fill opacity=.7] (5-2.corner 2)--(4-0.corner 1)--(4-1.corner 1)--
(2-1.corner 1)--(3-2.corner 3)--(4-4.corner 1)--(5-4.corner 2)--cycle;
\draw (4-1.corner 1) -- (4-3.corner 1) (4-2.corner 1)--(2-1.corner 1);
\end{scope}
\end{tikzpicture}
\end{document}