13 | * Created by jorgheymans on 12/05/16. 14 | */ 15 | public class TheFont { 16 | 17 | private Font font; 18 | 19 | public TheFont(File fontFile, String fontStyle, String fontName, int fontSize) throws Exception { 20 | GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 21 | ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, fontFile)); 22 | font = new Font(fontName, getFontStyle(fontStyle == null ? fontFile.getName() : fontStyle), fontSize); 23 | } 24 | 25 | public void paint(Graphics2D g, String glyph, int canvasWidth, int canvasHeight) { 26 | g.setFont(font); 27 | g.setColor(Color.WHITE); 28 | g.fillRect(0, 0, canvasWidth, canvasHeight); 29 | FontMetrics fm = g.getFontMetrics(); 30 | int x = (canvasWidth - fm.stringWidth(glyph)) / 2; 31 | // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen) 32 | int y = ((canvasHeight - fm.getHeight()) / 2) + fm.getAscent(); 33 | g.setColor(Color.BLACK); 34 | g.drawString(glyph, x, y); 35 | } 36 | 37 | /** 38 | * @param fontStyle 39 | * @return 40 | */ 41 | protected int getFontStyle(String fontStyle) { 42 | if (fontStyle.toLowerCase().contains("regular")) { 43 | return Font.PLAIN; 44 | } else if (fontStyle.toLowerCase().contains("italic")) { 45 | return Font.ITALIC; 46 | } else if (fontStyle.toLowerCase().contains("bold")) { 47 | return Font.BOLD; 48 | } else if (fontStyle.toLowerCase().contains("bolditalic")) { 49 | return Font.BOLD + Font.ITALIC; 50 | } 51 | throw new IllegalArgumentException("cannot parse fontstyle " + fontStyle); 52 | } 53 | } 54 | --------------------------------------------------------------------------------