Graphics2D.drawString 中换行符的问题

2022-08-31 19:49:16

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

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

答案 1

该方法不处理换行。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());
}

下面是一个完整的示例来给你这个想法:

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);
    }
}

这给出了以下结果:

enter image description here


答案 2

我刚刚做了一个通过给出线宽来自动绘制长文本拆分的方法。

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);
        }
    }
}