John:

There's no API in JDK 1.3.1 or prior that will get you what you want.  You can
get close, by getting the outline of the text and taking its bounds.  TextLayout
can be used to get an outline of a line of text, or you can use glyphVector to
get the bounds of individual glyphs (but note that Font.createGlyphVector does
not support international text well).  Unfortunately, since text rendering is
often done using hinted bitmaps, some of the bits might fall outside the outline
bounds. Your only precise, reliable option is to draw the text into a buffer and
then scan the buffer for the bounds of the bits.  Ugly and slow, but effective.

In JDK 1.4 there is API on glyphVector that returns a rect, in pixel
coordinates, that encloses the pixels of the rendered glyphs.  It is a bit
complex to construct glyphVectors for arbitrary text-- e.g. Hebrew bidirectional
text requires multiple glyphVectors-- but if your text is simple enough, and you
can use JDK 1.4, this would be another option.

If you don't need exact bounds, but just something 'close enough', you might try
using the outline technique and then expanding the rectangle by a pixel or two.
For almost all reasonably hinted text this will end up enclosing all of the
pixels.  It depends on whether the extra pixel or so of unnecessary bounds is
acceptable to you.

Doug


> I need to draw an opaque backing rectangle around some text I'm drawing and I
can't figure out how to get the bounds of the actual pixels that are drawn for
the text string. I've used the getStringBounds method on the FontMetrics class
but it leaves extra space above the top of the tallest character and below the
baseline(this particular text string doesn't go below the baseline).
>
> What's the best way to accurately find out the minimum bounding box that
encloses my text?
>
> Thanks,
>
> John  (using 1.3.1)

===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff JAVA2D-INTEREST".  For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".

Reply via email to