use graphics.drawText(String, x, y) to draw a stri

2019-07-25 13:11发布

问题:

I am making a custom Field representing an image and a label near it. I am drawing the image by graphics.drawBitmap(...)

Nw for the text, I am using graphics.drawText(String, x, y); but if the text it bigger than the display, it doesn't return to the line. I tried to add \n but that didn't solve the problem.

How can I draw a text that can expand on several lines?

Thanks,

回答1:

I found a solution to the problem. You can find it below for those who are interested in this question:

public void drawMultipleLines(Graphics graphics, String text, int X, int Y, int XavailableSpace) {
    String[] texts = UiSpliter.split(text, " "); //UiSpliter is a class that will split the string into string array based on the ' ' character
    int x = X;
    int y = Y;
    for (int i = 0 ; i < texts.length ; i ++) {
        if (x + getFont().getAdvance(texts[i]) - X > XavailableSpace) {
            if (!(x == X)) {
                x = X;
                y = y + getFont().getHeight();
            }
        }
        graphics.drawText(texts[i] + " ", x, y);
        x += getFont().getAdvance(texts[i] + " ");
    }
}


回答2:

As this answer says :

The drawString method does not handle new-lines, so is drawText

You'll have to split the string on new-line characters yourself and draw the lines one by one with a proper vertical offset.See that answer for details.



回答3:

You can use AttributedCharacterIterator,TextLayout and LineBreakMeasurer classes as explained in this Java Tutorial.