Skip to content

Instantly share code, notes, and snippets.

@hakanai
Last active February 3, 2018 05:03
Show Gist options
  • Save hakanai/a0cd679cd86f300885eab780f66c004c to your computer and use it in GitHub Desktop.
Save hakanai/a0cd679cd86f300885eab780f66c004c to your computer and use it in GitHub Desktop.
Generates a hex grid image
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class MakeStencilScannerGrid {
public static void main(String[] args) throws Exception {
int imageSize = 1024;
Color evenColour = new Color(0, 128, 128);
Color oddColour = new Color(64, 64, 64);
BufferedImage numberImage = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
BufferedImage maskImage = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D numberImageGraphics = null;
Graphics2D maskImageGraphics = null;
try {
numberImageGraphics = numberImage.createGraphics();
maskImageGraphics = maskImage.createGraphics();
numberImageGraphics.setFont(new Font("Monaco", Font.PLAIN, 32));
FontMetrics fontMetrics = numberImageGraphics.getFontMetrics();
int textHeight = fontMetrics.getAscent();
int textWidth = fontMetrics.stringWidth("00");
int cellSize = (imageSize / 16);
for (int row = 0; row < 16; row++) {
for (int column = 0; column < 16; column++) {
int number = row * 16 + column;
String numberString = Integer.toHexString(row) + Integer.toHexString(column);
boolean evenCell = ((column + row) % 2) == 0;
int x1 = column * (imageSize / 16);
int y1 = row * (imageSize / 16);
numberImageGraphics.setColor(evenCell ? evenColour : oddColour);
numberImageGraphics.fillRect(x1, y1, cellSize, cellSize);
numberImageGraphics.setColor(evenCell ? oddColour : evenColour);
numberImageGraphics.drawString(numberString, x1 + (cellSize - textWidth) / 2, y1 + (cellSize + textHeight) / 2);
maskImageGraphics.setColor(new Color(number, number, number));
maskImageGraphics.fillRect(x1, y1, cellSize, cellSize);
}
}
} finally {
if (numberImageGraphics != null) {
numberImageGraphics.dispose();
}
if (maskImageGraphics != null) {
maskImageGraphics.dispose();
}
}
ImageIO.write(numberImage, "PNG", new File("StencilScannerGrid.png"));
ImageIO.write(maskImage, "PNG", new File("StencilScannerMask.png"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment