Suzan Cioc
Suzan Cioc

Reputation: 30097

How to fit font into pixel size in Java? How to convert pixels to points?

I need to create font of a givens size in pixels.

Java's Font class constructor requires font size expressed in points. Points are physical length while pixels are digitizes. So I need dpi.

It is said in manual, that this value is contained inside FontRenderContext.getTransform().

I found, that in my case, scaling is one, i.e. pixels = points.

Unfortunately, creating font of size 100 creates bigger image.

For example, code below

    BufferedImage ans = new BufferedImage(width, height, imageType);
    Font font = new Font(fontName,fontStyle,height);

    Graphics2D g2 = ans.createGraphics();

    g2.setFont(font);

    FontMetrics fm = g2.getFontMetrics();
    FontRenderContext frc = g2.getFontRenderContext();

    System.out.println("height=" + height);
    System.out.println("frc.getTransform()=" +frc.getTransform());
    System.out.println("g2.getTransform()=" +g2.getTransform());
    System.out.println("fm.getAscent()+fm.getDescent()="+fm.getAscent()+"+"+fm.getDescent()+"="+(fm.getAscent()+fm.getDescent()));


    g2.drawString(str, 0, fm.getAscent());

gives

height=100
frc.getTransform()=AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
g2.getTransform()=AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
fm.getAscent()+fm.getDescent()=93+20=113

How to fit?

Upvotes: 0

Views: 5273

Answers (2)

Max
Max

Reputation: 109

// using javafx: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/text/package-summary.html 
Text text = new Text("Hello World");
Font font = Font.font("Arial", 10); // 10 is point size
text.setFont(font);
double width = text.getLayoutBounds().getWidth(); // width is pixel size

Upvotes: 1

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

I've used this code to determine the size of a String in pixels when drawing the String.

The x and y calculation centers the String in the drawing area. The y calculation looks odd because the y origin is at the bottom left, not the top left.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (font == null) {
        return;
    }

    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();
    TextLayout layout = new TextLayout(sampleString, font, frc);
    Rectangle2D bounds = layout.getBounds();

    int width = (int) Math.round(bounds.getWidth());
    int height = (int) Math.round(bounds.getHeight());
    int x = (getWidth() - width) / 2;
    int y = height + (getHeight() - height) / 2;

    layout.draw(g2d, (float) x, (float) y);
}

Upvotes: 1

Related Questions