Wasting my time… Writing on a blog.

My page of ramblings

Java and its wonderful graphics class March 16, 2009

Filed under: Uncategorized — jordoex @ 2:22 pm
Tags: , ,

I could probably implement an entire windowing system using just java Graphics2D primitives.  They’re so useful, probably one of the best things designed right inside a language.

However, word wrap is a fairly annoying thing, but at least I found a code snippet that outlines it better than my original idea here.  It’s kinda ugly, but still not nearly as ugly as what you have to hack with c strings.

Here’s my slightly different implementation; it’s still pretty much the same, and i’m still gonna tweak it a bit more.  I’m just glad it works.

   private void drawStringRect(Graphics2D graphics, RectangularShape bounds,
            float interline, String s) {

            AttributedString as = new AttributedString(s);
            as.addAttribute(TextAttribute.FOREGROUND, graphics.getPaint());
            as.addAttribute(TextAttribute.FONT, graphics.getFont());

            FontRenderContext frc = new FontRenderContext(null, true, false);

            LineBreakMeasurer lbm = new LineBreakMeasurer(as.getIterator(), frc);

            int y_current = (int) bounds.getMinY();

            float width = (float) bounds.getWidth();

            while (lbm.getPosition() < s.length()) {
                TextLayout tl = lbm.nextLayout(width);
                y_current += tl.getAscent();
                tl.draw(graphics, (float)bounds.getMinX(), y_current);
                y_current += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
                if (y_current > bounds.getMaxY()) {
                    break;
                }
            }
        }
 

Leave a Reply