Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java rotated text has reversed characters sequence

In a subclass of a JPanel I am doing this:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;        
    g2d.rotate(Math.toRadians(90.));
    g2d.drawString(aString, 40, -40);
}

The letters are rotated correctly, but the second one is not in the expected position below the first (to its right, in the rotated space), but is above it (to its left), the third is above (to the left of) the second, etc. Changing the rotation angle to 45 degrees results in each character being rotated 45 degrees cw, as expected, but the row of characters being rotated 45 degrees ccw, which is consistent with both rotations being halfway toward the result for 90 degrees.

At 0 degrees rotation the text appears correctly.

I'm developing with NetBeans 7.1.2 on Mac OS X 10.8.2. Same version of NetBeans on Win 7 SP1 does not have the problem.

What could be causing this?

like image 805
eclux Avatar asked Jan 28 '13 19:01

eclux


3 Answers

I've found an odd solution for this problem (that matches the oddness of the bug)

FontRenderContext frc = new FontRenderContext(g2.getTransform(), true, true);

g2.drawGlyphVector(currentFont.createGlyphVector(frc, aString), textX, textY);

For some reason setting anti-aliasing to true on the FontRenderContext will cause it to act correctly. Seems that someone is missing a minus sign somewhere in the render code, or misunderstood the spec they were writing for!

like image 176
Todd Avatar answered Sep 21 '22 10:09

Todd


We're seeing the same thing. We have code that works great on Windows spanning most of the JRE 6 and 7 versions. The same code today exhibited the rotated backwards characters problem. The problem JRE version is 1.6.0_37 on OS X. It may or may not have worked before on OS X. 99.9% of our users are on Windows.

One workaround would be to render the text to a BufferedImage and then rotate the image. That's a method I've used to get a better result visually for rotating text 20-30 degrees or so.

like image 30
Chris Holt Avatar answered Sep 22 '22 10:09

Chris Holt


The method of AffineTransformation posted by user1181445 below was working for me for all platforms, including the problematic OSX, up until the most recent Java OSX update (version 7, update 55). Now the rotated text is messed up, but only on the applet. I don't see a problem in the standalone version of our app.

like image 26
William Nelson Avatar answered Sep 21 '22 10:09

William Nelson