Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to drawString() from ascender line

Tags:

java

java-2d

I am displaying some graphics text on Screen by using the drawString(. . .) function of Java2D Library.

Refering to the figure in this article i want my string to be drawn from Ascender Line rather than BaseLine. In simple words is there any way to calculate the height b/w ascender line and Base Line?

like image 584
Jame Avatar asked Nov 08 '11 13:11

Jame


3 Answers

A normal drawString will align the base-line with the y-argument. If you want to draw the string so that the ascent-line is align with y, you need to pass y + fm.getAscent() where fm is the current FontMetrics object. See example below.

This screen shot:

enter image description here

is produced by this code:

FontMetrics fm = g.getFontMetrics();

g.setColor(Color.RED);
g.drawLine(10, 10, 100, 10);

g.setColor(Color.BLACK);
g.drawString("Hello frog", 10, 10 + fm.getAscent());
like image 113
aioobe Avatar answered Nov 01 '22 23:11

aioobe


You can get the FontMetrics object of the used font, and determine the ascent using getAscent() or getMaxAscent(), whichever is appropriate in your case.

like image 3
king_nak Avatar answered Nov 02 '22 01:11

king_nak


Add FontMetrics.getAscent() to the y position before rendering.

like image 1
Aaron Digulla Avatar answered Nov 01 '22 23:11

Aaron Digulla