如何用 tikz 制作谢尔宾斯基方形地毯?我在网上看到很多谢尔宾斯基三角形,但我找不到任何正方形。有人知道怎么做吗?
答案1
可能要花很长时间...
\documentclass[tikz,border=5]{standalone}
\newcount\sierpinskiorder
\newcommand\sierpinskicarpet[2][]{%
\tikzset{sierpinski/.cd,#1}%
\sierpinskiorder=#2\relax%
\path [sierpinski/background/.try] (0,0) rectangle (1,1);
\SierpinskiCarpet}
\def\SierpinskiCarpet{{%
\ifnum\sierpinskiorder>0\relax
\path [sierpinski/foreground/.try] (1/3, 1/3) rectangle ++(1/3, 1/3);
\advance\sierpinskiorder by -1\relax
\foreach \x in {0,...,2}{\foreach \y in {0,...,2}{
\begin{scope}[shift={(\x/3,\y/3)},scale=1/3]
\SierpinskiCarpet
\end{scope}
}}
\fi
}}
\begin{document}
\begin{tikzpicture}
\sierpinskicarpet[foreground/.style={fill=white},
background/.style={top color=blue, bottom color=red}]{5}
\end{tikzpicture}
\end{document}