Link to home
Start Free TrialLog in
Avatar of dr0zaxx
dr0zaxx

asked on

Draw string with Graphics2D

Hi,

I'm having a major obstacle in my Swing application. According to the API, the drawString method in Graphics2D will make the lefthand side of the baseline the x and y (x and y are the arguments of the drawString method).

Is there any way I can make the x and y the top left hand corner of the string? It is something like shifting the anchor point, so that the top left hand corner of the string will be at x and y.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Subtract the height of the string from y.
Use the FontMetrics class to get the height of the string
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
Avatar of Emilda
Emilda

FontMetrics f = g.getFontMetrics();
int fascent = f.getAscent();
       
g.drawString("Hello", x, fascent);
ASKER CERTIFIED SOLUTION
Avatar of Webstorm
Webstorm

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
to get the actual bounds of the string use:

 Rectangle2D bounds = fm.getStringBounds(s, g2d);

you can then use those bounds to offset the position to paint it.
Avatar of dr0zaxx

ASKER

Thanks for the responses.