Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fonts - How to position top-left corner of a string?

Tags:

java

fonts

swing

Let's say I want to use the java.awt.Graphics.drawString(String str, int x, int y) method to draw a string at some specific coordinates, say somewhere like (300, 300). However the drawString() method will always position the bottom-left-hand corner of the string at those coordinates, not the top-left-hand corner which is what I want.

What's an easy way to draw the top-left hand corner of a string at a specified coordinate? I am aware of the java.awt.FontMetrics utility class but quite sure if it can be helpful.

like image 993
zxgear Avatar asked Jan 08 '23 13:01

zxgear


2 Answers

FontMetrics is the class to use:

public static int getStringAscent(Graphics page, Font f, String s) {
    // Find the size of string s in the font of the Graphics context "page"
    FontMetrics fm   = page.getFontMetrics(f);
    return fm.getAscent();
}

The ascent is the maximum height glyphs of the given string raise from the baseline. The start of the baseline is the reference point for the drawString method, and therefore the ascent is the distance with which you must adjust the coordinate. If you use this to draw a String using Graphics2D g:

g.drawString(msg, x, y);

you can shift it down by the ascender height for Font f:

Font small = new Font("Helvetica", Font.BOLD, 24);
FontMetrics metrics = getFontMetrics(small);
int d = metrics.getAscent();

g.drawString(msg, x, y + d );
like image 111
laune Avatar answered Jan 14 '23 13:01

laune


Try this:

FontMetrics metric = g.getFontMetrics(g.getFont());
g.drawString(str, x, y + metric.getAscent() - metric.getDescent() - metric.getLeading());
like image 36
user148865 Avatar answered Jan 14 '23 14:01

user148865