Here you can find the source of setFontOfPixelHeight(Graphics2D g, int style, double targetSize)
Parameter | Description |
---|---|
g | a parameter |
style | The font style (e.g. Font.PLAIN) |
targetSize | The target height of the line |
private static void setFontOfPixelHeight(Graphics2D g, int style, double targetSize)
//package com.java2s; import java.awt.Font; import java.awt.Graphics2D; public class Main { /**/*from w w w.j a v a 2 s .c om*/ * Sets the font on the given graphics context to have the given style and target size * @param g * @param style The font style (e.g. Font.PLAIN) * @param targetSize The target height of the line */ private static void setFontOfPixelHeight(Graphics2D g, int style, double targetSize) { // Likely DPI ranges for a monitor: 120 to 500 pixels per inch (via wikipedia) // An inch is 72 points, so range is something like 1 pixel per point to 8 pixels per point // So we explore from 1 point, up to the desired pixel size in points. // e.g. if we want 40 pixels, then a 40 point font is going to be bigger than 40 pixels if the display is above 72 DPI Font font = new Font("SansSerif", style, 1); for (int i = 1; i < targetSize; i++) { Font bigger = font.deriveFont((float) i); g.setFont(bigger); // This string should be full height in the font: if (bigger .getLineMetrics("WBLMNqpyg", g.getFontRenderContext()) .getHeight() < targetSize) // getStringHeight(g, "WBLMNqpyg") < targetSize) { font = bigger; } else { break; // Too big; keep previous } } g.setFont(font); } }