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.
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.
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();
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
FontMetrics f = g.getFontMetrics();
int fascent = f.getAscent();
g.drawString("Hello", x, fascent);
int fascent = f.getAscent();
g.drawString("Hello", x, fascent);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
Rectangle2D bounds = fm.getStringBounds(s, g2d);
you can then use those bounds to offset the position to paint it.
ASKER
Thanks for the responses.
:-)