use graphics.drawText(String, x, y) to draw a string on several lines

浪子不回头ぞ 提交于 2019-12-24 12:51:32

问题


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.



来源:https://stackoverflow.com/questions/7912880/use-graphics-drawtextstring-x-y-to-draw-a-string-on-several-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!