(Translated by https://www.hiragana.jp/)
Hilbert curve | TikZ example
 

Example: Hilbert curve

Published 2007-05-16 | Author: Marc van Dongen

A Hilbert curve drawn using recursive TeX macros and PGF.

Warning. Drawing Hilbert curves of order n > 6 is not recommended. Computing time increases exponentially and TeX will soon run out of memory resources.

Author:Marc van Dongen
Source:pgf-users mailing list

Download as: [PDF] [TEX]

Hilbert curve

Do you have a question regarding this example, TikZ or LaTeX in general? Just ask in the LaTeX Forum.
Oder frag auf Deutsch auf TeXwelt.de. En français: TeXnique.fr.

% Author: Marc van Dongen
\documentclass[12pt]{article}

\usepackage{tikz}
\usepackage{ifthen}

\usepackage[position=top,labelformat=empty]{subfig}
\newdimen\HilbertLastX
\newdimen\HilbertLastY
\newcounter{HilbertOrder}

\def\DrawToNext#1#2{%
   \advance \HilbertLastX by #1
   \advance \HilbertLastY by #2
   \pgfpathlineto{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
   % Alternative implementation using plot streams:
   % \pgfplotstreampoint{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
}

% \Hilbert[right_x,right_y,left_x,left_x,up_x,up_y,down_x,down_y]
\def\Hilbert[#1,#2,#3,#4,#5,#6,#7,#8] {
  \ifnum\value{HilbertOrder} > 0%
     \addtocounter{HilbertOrder}{-1}
     \Hilbert[#5,#6,#7,#8,#1,#2,#3,#4]
     \DrawToNext {#1} {#2}
     \Hilbert[#1,#2,#3,#4,#5,#6,#7,#8]
     \DrawToNext {#5} {#6}
     \Hilbert[#1,#2,#3,#4,#5,#6,#7,#8]
     \DrawToNext {#3} {#4}
     \Hilbert[#7,#8,#5,#6,#3,#4,#1,#2]
     \addtocounter{HilbertOrder}{1}
  \fi
}


% \hilbert((x,y),order)
\def\hilbert((#1,#2),#3){%
   \advance \HilbertLastX by #1
   \advance \HilbertLastY by #2
   \pgfpathmoveto{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
   % Alternative implementation using plot streams:
   % \pgfplothandlerlineto
   % \pgfplotstreamstart
   % \pgfplotstreampoint{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
   \setcounter{HilbertOrder}{#3}
   \Hilbert[1mm,0mm,-1mm,0mm,0mm,1mm,0mm,-1mm]
   \pgfusepath{stroke}%
}

\begin{document}
\begin{figure}%
    \centering
    % draw Hilbert curves of order n=1,...,5
    % Warning! Curves with order > 6 may crash TeX
    \subfloat[$n=1$]{\tikz[scale=18] \hilbert((0mm,0mm),1);}~~
    \subfloat[$n=2$]{\tikz[scale=6] \hilbert((0mm,0mm),2);}~~
    \subfloat[$n=3$]{\tikz[scale=2.6] \hilbert((0mm,0mm),3);}~~
    \subfloat[$n=4$]{\tikz[scale=1.2] \hilbert((0mm,0mm),4);}~~
    \subfloat[$n=5$]{\tikz[scale=0.58] \hilbert((0mm,0mm),5);}%
\end{figure}%

\end{document}

Comments

Adding comments is currently not enabled.