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.
LVL 1
dr0zaxxAsked:
Who is Participating?
 
WebstormCommented:
Hi dr0zaxx,


FontMetrics f = g.getFontMetrics();
int yf = f.getMaxAscent();
       
g.drawString("Hello", x, yf + y);
0
 
objectsCommented:
Subtract the height of the string from y.
0
 
objectsCommented:
Use the FontMetrics class to get the height of the string
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
EmildaCommented:
FontMetrics f = g.getFontMetrics();
int fascent = f.getAscent();
       
g.drawString("Hello", x, fascent);
0
 
objectsCommented:
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.
0
 
dr0zaxxAuthor Commented:
Thanks for the responses.
0
 
WebstormCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.