Centering Text?

C

Chris Rehm

I am using 1.4.2 on Windows XP.

I print various geometric shapes on a page and I want to number them,
printing the numbers centered in the middle of the shape.

I've tried
//fm is the FontMetrics for the current font.
float cx = dl.getLocationX(); // Current coordinates
float cy = dl.getLocationY();

cy = cy + ((float) fm.getAscent() / 2);
cx = cx - ((float) fm.stringWidth(numberString) / 2);

g2.drawString(numberString, cx, cy);

and
Rectangle2D r = fm.getStringBounds(numberString,g2);

float cx = dl.getLocationX();
float cy = dl.getLocationY();

cy = (float)(r.getHeight()/2) + cy;
cx = cx - (float)(r.getWidth()/2);

g2.drawString(numberString, cx, cy);

but in both cases my text is moved too far left and too far down.

The rest of the graphics I'm printing look great, I'd love to get this
fixed. What am I missing in FontMetrics?

--
Chris Rehm
(e-mail address removed)

Thou shalt not avenge, nor bear any grudge against the children of thy
people, but shalt love thy neighbour as thyself. [Lev. 19:18]
 
Z

ZB

Try with :

float cx = (float) dl.getBounds2D.getCenterX();
float cy = (float) dl.getBounds2D.getCenterY();

or something like that (without getBounds2D). Anyway, what type is variable
dl ?

Regards, Zoran.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Image not printing 1

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top