javatextgraphicsrenderingawt

How do i render wrapped text on an image in java


Using Java, is there any built-in way to render text so that its limited to a rectangle on a graphics2D object?

I know I can use Graphics2D.drawString but it only draws a sinlge line of text.

I also know that I can use

FontMetrics fm= graphics.getFontMetrics(font);
Rectangle2D rect=fm.getStringBounds("Some Text",graphics);

to get the information about the bounds of a string when rendered using some Font font on some Graphics2D graphics object.

So I could start looping, breaking my string and so on to force it to fit inside some rectangle.

But I would much prefer not to have to write those...

Is there any ready made function that will do this for me?


Solution

  • Use temporary JTextArea to do perfect line wrapping with ~10 lines of code:

    static void drawWrappedText(Graphics g, String text, int x, int y, int w, int h) {
        JTextArea ta = new JTextArea(text);
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setBounds(0, 0, w, h);
        ta.setForeground(g.getColor());
        ta.setFont(g.getFont());
        Graphics g2 = g.create(x, y, w, h); // Use new graphics to leave original graphics state unchanged
        ta.paint(g2);
    }