Search code examples
javaswinggraphicsgraphics2d

Graphics2D - Text is HUGE in scaled coordinate space


The first "foo" is normal, but the second one is so huge I can only see the base of the "f". The font-size is the default.

    BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    Shape ellipse = new Ellipse2D.Double(0, 0, 1.0, 1.0);
    g2.setPaint(Color.RED);
    g2.drawString("foo", 100, 100);
    g2.scale(500.0f / length, 500.0f / length);
    g2.drawString("foo", 1, 1);

Changing the font size will not help because it only allows int sizes and the size that would make sense for the scale is something like 0.02.

The reason I need to draw the text while in scaled space is because I am drawing a grid of nodes and I want to scale the coordinates to the number of nodes in each dimension. That way I do not have to do complicated calculations.

I need the text to label the edges.

Update: I am able to get the text by doing the following sequence each time I want to draw the text: saving the transform, translating to the desired location in scaled space, unscaling, drawing the text at (0, 0), and restoring the transform.


Solution

  • You can use Font method

    public Font deriveFont(float size)
    

    to obtain desired font size font. Guess the 0.02 shoud be fine.