View Javadoc
1   package org.davidmoten.hilbert;
2   
3   import java.awt.BasicStroke;
4   import java.awt.Color;
5   import java.awt.Graphics2D;
6   import java.awt.image.BufferedImage;
7   import java.io.File;
8   import java.io.IOException;
9   import java.math.BigInteger;
10  
11  import javax.imageio.ImageIO;
12  
13  import org.davidmoten.hilbert.exceptions.IORuntimeException;
14  
15  public final class HilbertCurveRenderer {
16  
17      private HilbertCurveRenderer() {
18          // prevent instantiation
19      }
20  
21      public static void renderToFile(int bits, int width, String filename) {
22          BufferedImage b = render(bits, width);
23          try {
24              ImageIO.write(b, "PNG", new File(filename));
25          } catch (IOException e) {
26              throw new IORuntimeException(e);
27          }
28      }
29  
30      public static BufferedImage render(int bits, int width) {
31          int dimensions = 2;
32          HilbertCurve c = HilbertCurve.bits(bits).dimensions(dimensions);
33          int n = 1 << bits;
34          int height = width;
35          BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
36          Graphics2D g = b.createGraphics();
37          g.setBackground(Color.white);
38          g.fillRect(0, 0, width, height);
39          g.setPaint(Color.black);
40          g.setStroke(new BasicStroke(0.5f));
41          int margin = 10;
42          int cellSize = (width - 2 * margin) / (n);
43          int x = margin + cellSize / 2;
44          int y = margin + cellSize / 2;
45          for (long i = 0; i < n * n; i++) {
46              long[] point = c.point(BigInteger.valueOf(i));
47              int x2 = (int) Math.round((double) point[0] / (n - 1) * (width - 2 * margin - cellSize) + margin)
48                      + cellSize / 2;
49              int y2 = (int) Math.round((double) point[1] / (n - 1) * (height - 2 * margin - cellSize) + margin)
50                      + cellSize / 2;
51              g.drawLine(x, y, x2, y2);
52              x = x2;
53              y = y2;
54          }
55          return b;
56      }
57  }