[en] How to word wrap text in Graphics2D.drawString in Java

Google wasn’t awfully helpful while I was searching for solution to word wrapping a text when drawing in Java, so let’s teach Google this: 😉

    private void drawStringRect(Graphics2D graphics, int x1, int y1, int x2, int y2, 
        float interline, String txt) {
        AttributedString as = new AttributedString(txt);
        as.addAttribute(TextAttribute.FOREGROUND, graphics.getPaint());
        as.addAttribute(TextAttribute.FONT, graphics.getFont());
        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = new FontRenderContext(null, true, false);
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
        float width = x2 - x1;

        while (lbm.getPosition() < txt.length()) {
            TextLayout tl = lbm.nextLayout(width);
            y1 += tl.getAscent();
            tl.draw(graphics, x1, y1);
            y1 += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
            if (y1 > y2) {
                break;
            }
        }
    }

Jedna myśl nt. „[en] How to word wrap text in Graphics2D.drawString in Java

  1. I am curious to find out what blog system you’re using? I’m having some minor security issues with my latest blog and I would like to find something more secure. Do you have any suggestions?|

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *