Text bounds

Hi

I am trying to do something really simple… at least I thought so.

I want to top-align a text in a certain area (on a Graphics2D). But unfortunately the string bounds are not exactly precise as for the upper bound. The attached screenshot shows, how the text is currently aligned. Can anyone tell me, how to get the height of the upper empty space? I wuld like the text to be at the top border just as it is on the left border.

Thanks in advance.

Marvin

Graphics2D.getFontMetrics().getMaxAscent()

Are you using FontMetrics.getStringBounds(…)? If so, you may need to draw the string to a buffer, scan for the first row with non-zero pixels, and draw the buffer with a suitable offset. I’m surprised that FontMetrics doesn’t have a way to get an individual character’s ascent and descent, but that’s the way it is.

Thanks for your help guys.

getMaxAscent() seems to return te same value as getAscent().

Yes, I am using getStringBounds(). And I tried to correct the y-offset through some values of getLineMetrics(). But that didn’t work. I definitely don’t want to scan for empty pixels, since I highly depend on maximum performance.

This solution seems to work:


offset_y = (int)( stringBounds.getHeight() - font.getSize2D() );

Marvin

You could do it as a one-off for each character, cache the values in an array, and then just scan the first line of the text to find the tallest one.

In LineMetrics, you can get the leading value for a line of text (which seems to be constant for a Font), but the leading is the amount of recommended pixel space to add between the bottom of the descent of one line, and the top of the ascent on another.

Sorry, I forgot about the descent. Here is what I did to put the text right at the top with no gap:


FontMetrics metrics = pGraphics.getFontMetrics();
strYPos = metrics.getAscent() - metrics.getDescent();