Graphics2D.drawString中的换行问题

pki*_*sky 47 java string newline graphics2d

g2是类的一个实例Graphics2D.我希望能够绘制多行文本,但这需要换行符.以下代码在一行中呈现.

String newline = System.getProperty("line.separator");
g2.drawString("part1\r\n" + newline + "part2", x, y);
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 82

drawString方法不处理新行.

你必须自己在新行字符上拆分字符串并逐行绘制具有适当垂直偏移的行:

void drawString(Graphics g, String text, int x, int y) {
    for (String line : text.split("\n"))
        g.drawString(line, x, y += g.getFontMetrics().getHeight());
}
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子来给你这个想法:

import java.awt.*;

public class TestComponent extends JPanel {

    private void drawString(Graphics g, String text, int x, int y) {
        for (String line : text.split("\n"))
            g.drawString(line, x, y += g.getFontMetrics().getHeight());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawString(g, "hello\nworld", 20, 20);
        g.setFont(g.getFont().deriveFont(20f));
        drawString(g, "part1\npart2", 120, 120);
    }

    public static void main(String s[]) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new TestComponent());
        f.setSize(220, 220);
        f.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

得出以下结果:

在此输入图像描述

  • ctrl + c,ctrl + v ...很棒`drawString`方法 (3认同)
  • 一个小注意事项:“FontMetrics.getAscent()”也应该用于字符串的正确定位(即使用“y +metrics.getAscent()”而不是仅使用“y”)。 (2认同)

小智 9

我只是通过给出线宽来自动绘制长文本分割的方法.

public static void drawStringMultiLine(Graphics2D g, String text, int lineWidth, int x, int y) {
    FontMetrics m = g.getFontMetrics();
    if(m.stringWidth(text) < lineWidth) {
        g.drawString(text, x, y);
    } else {
        String[] words = text.split(" ");
        String currentLine = words[0];
        for(int i = 1; i < words.length; i++) {
            if(m.stringWidth(currentLine+words[i]) < lineWidth) {
                currentLine += " "+words[i];
            } else {
                g.drawString(currentLine, x, y);
                y += m.getHeight();
                currentLine = words[i];
            }
        }
        if(currentLine.trim().length() > 0) {
            g.drawString(currentLine, x, y);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)