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.
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 );
Try this:
FontMetrics metric = g.getFontMetrics(g.getFont());
g.drawString(str, x, y + metric.getAscent() - metric.getDescent() - metric.getLeading());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With