Код: Выделить всё
// params
File workingDir = new File("/Users/vigo/test-dir/");
int verticalPadding = 2;
int horizontalPadding = 2;
File fontFile = new File(workingDir, "Arabella.ttf");
String text = "Hello World";
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(40f);
// calculate bounds
BufferedImage temp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = temp.createGraphics();
FontMetrics fm = g2d.getFontMetrics(font);
// get image width and height
int width = fm.stringWidth(text) + (horizontalPadding * 2);
int height = (int) Math.ceil(fm.getAscent() + fm.getDescent() + fm.getLeading()) + (verticalPadding * 2);
// get x and y draw points
int x = horizontalPadding;
int y = verticalPadding + fm.getAscent();
g2d.dispose();
// create the actual image and draw text
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.BLACK);
g2d.setFont(font);
g2d.drawString(text, x, y);
g2d.dispose();
ImageIO.write(image, "png", new File(workingDir, "text-img.png"));

Но при небольшом количестве шрифтов пример arabella возвращает неправильный "Y" значение:

Есть ли лучший способ добиться одинаковой визуальной высоты разных шрифтов при рендеринге текстовых изображений?
Подробнее здесь: https://stackoverflow.com/questions/797 ... t-for-some
Мобильная версия