使用graphics.drawText(String, x, y) 在多行上绘制字符串

发布于 2024-12-12 04:32:02 字数 237 浏览 0 评论 0原文

我正在制作一个代表图像及其附近标签的自定义字段。 我正在通过 graphics.drawBitmap(...) 绘制图像

Nw 对于文本,我正在使用 graphics.drawText(String, x, y); 但如果文本大于显示,它不会返回到该行。我尝试添加 \n 但这并没有解决问题。

如何绘制可以扩展为多行的文本?

谢谢,

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦一生花开无言 2024-12-19 04:32:02

我找到了解决问题的方法。对这个问题感兴趣的人可以在下面找到它:

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] + " ");
    }
}

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] + " ");
    }
}
许一世地老天荒 2024-12-19 04:32:02

正如这个答案所说:

drawString 方法不处理换行符,也是如此 drawText

您必须自己在换行符上拆分字符串并绘制一行一行地具有适当的垂直偏移。有关详细信息,请参阅该答案。

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.

云淡月浅 2024-12-19 04:32:02

您可以使用 AttributedCharacterIterator、TextLayout 和 LineBreakMeasurer 类,如Java 教程。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文