views:

46

answers:

1

Currently I have a text object that I need to determine its bounds. I used to use the graphics object to obtain the font metrics of the text I am trying to draw, but since I added functionality to rotating the object(and possibly more) I need a better way to get the bounds of this object. I have looked multiple places and nothing has really worked for me as of yet. Here is my most current attempt:

//This is the bounding box edges 0: left, 1: right 2: top 3: bottom  
int toReturn[] = new int[4];
//this.transform is the AffineTransform for the text Object(currently only
//rotated)
FontRenderContext frc = new FontRenderContext(this.transform,true,false);
TextLayout tl = new TextLayout(this.typedText,this.font,frc);
Rectangle2D bb = tl.getBounds();
toReturn[0] = (int)(bb.getX());
toReturn[1] = (int)(bb.getX()+bb.getWidth());
toReturn[2] = (int)(bb.getY());
toReturn[3] = (int)(bb.getY()+bb.getHeight());

Is this the proper way to get the bounding box for transformed text?

+1  A: 

No, the AffineTransform supplied to FontRenderContext "is used to scale typographical points to pixels in this FontRenderContext." You should be able to use createTransformedShape() on the boundary to get the result you want.

trashgod
Thanks for the reply (and the edit), im not sure quite how to format my code again in this reply so i apologize, but if I understand you properly is this what you mean:Shape shape = transform.createTransformedShape("some Shape");The only question I would have now is what shape would be provided to that method?tl.getBounds()?
heater
@heater: Yes, `tl.getBounds()` or `font.getStringBounds()`; it's very convenient for `contains()` testing. If you need the transformed coordinates themselves, use one of the `transform()` methods of `AffineTRansform`. BTW, use back-ticks for in-line code; indent four for code listings.
trashgod
@trashgod: thanks for the quick response and info for in-line code, this seems to work how I want it to :)
heater
@heater: Glad to help. You can also click on any "edited _n_ _units_ ago" link to peek at interesting effects.
trashgod