Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 240
  • Last Modified:

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.
0
dr0zaxx
Asked:
dr0zaxx
1 Solution
 
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
 
EmildaCommented:
FontMetrics f = g.getFontMetrics();
int fascent = f.getAscent();
       
g.drawString("Hello", x, fascent);
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
WebstormCommented:
Hi dr0zaxx,


FontMetrics f = g.getFontMetrics();
int yf = f.getMaxAscent();
       
g.drawString("Hello", x, yf + y);
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

Featured Post

Get expert help—faster!

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

Tackle projects and never again get stuck behind a technical roadblock.
Join Now