Search code examples
javaimageimage-manipulationgraphics2d

Java Graphics Font - How to make sure the text is kept in one line?


Using Graphics2D, I'd like to show a text inside my image, but I'd like it to be shown in one line. That means if the text is longer than the image, the size will be reduced (adapted)

How could I do ?

So far, here's what I did, but I'm sure it's really bad.

int fontSize = 66;
FontRenderContext frc = new FontRenderContext(null, true, true);
element = null;

do { // we turn until the size goes into the image
    fontSize -= 2;
    layout = new TextLayout(myText, new Font(font, Font.BOLD, fontSize), frc);
    element = layout.getPixelBounds(null, 0, 0);

    if (fontSize <= 12) {
        throw new Exception ("Title too long.");
    }
} while(element.width > image.getWidth());

How can I do ?

Thanks for your help.


Solution

  • I've had to do the same kind of thing when putting text inside a circle for a particular display. The only thing you can reasonably do better on is, instead of making your search a linear search, make it binary. This will give you better overall performance. Other than this, your approach is fine - I think this is about as good as you can do with fitting text to specific on-screen dimensions in Java.

    Couple of coding semantics issues too - this would probably be more readable if you did it in a regular while-loop.

    Another issue is the Exception you're throwing. It'd probably be better to put this in a function that returned some value indicating whether the text could be drawn on a particular image or not. It's never a good thing to use thrown Exceptions to determine program logic if you can get the same behavior while using a simple conditional statement.