Captain Head
Captain Head

Reputation: 343

Graphics2D text draws at different position when using draw position vs translation transform

If I do this:

g.drawString("9", (float) 10, (float) 50);

the text "9" will be drawn at pixel x-position 10.

Similarly, if I do this:

g.translate(10, 0);
g.drawString("9", (float) 0, (float) 50);

the text will again be drawn at x-position 10.

However, if I do this:

g.translate(9.5, 0);
g.drawString("9", (float) 0.5, 50);

the text will appear 1 pixel to the right, presumably at x-position 11.

Here's what it looks like (zoomed in 4x) with a vertical reference line.

example image

I assume this is some kind of rounding error going on in the Graphics renderer. Is there a way to ensure the 3rd "9" draws at the same x-position as the previous two?

Upvotes: 2

Views: 153

Answers (1)

WoDoSc
WoDoSc

Reputation: 2618

You could round yourself your coordinates and pass to the Graphics2D only integers.

Upvotes: 1

Related Questions