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

2019-07-25 12:49发布

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,

3条回答
一纸荒年 Trace。
2楼-- · 2019-07-25 13:12

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.

查看更多
The star\"
3楼-- · 2019-07-25 13:15

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] + " ");
    }
}
查看更多
Animai°情兽
4楼-- · 2019-07-25 13:20

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

查看更多
登录 后发表回答