gpt4 book ai didi

java - LineBreakMeasurer 产生的结果不同于 MS Word/LibreOffice

转载 作者:行者123 更新时间:2023-11-30 09:24:28 28 4
gpt4 key购买 nike

在 swing 应用程序中,我需要预见字符串的文本换行,就像将其放入 MS Word 或 LibreOffice 等文字处理器程序中一样。提供相同宽度的可显示区域,相同的字体(字体和大小)和相同的字符串如下:

  • 可显示区域宽度:179 毫米(在 .doc 文件中,设置 A4 纵向页面 - 宽度 = 210 毫米,左边距 = 20 毫米,右边距 = 11 毫米;段落格式为零边距)
  • Times New Roman 字体,14 号
  • 测试字符串:Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vsstrt vsip d asfd eacc

结果:

  • 在 MS Word 和 LibreOffice 上,该测试字符串显示在单行中,没有发生文本换行。
  • 我的以下程序报告发生文本换行,2 行

    第 1 行:Tadf fdas fdas daebjnbvx dasf opqwe dsa:dfa fdsa ewqnbcmv caqw vsrt vsip d asfd

    第 2 行:eacc

能否在swing中实现和MS Word一样的文字环绕效果?代码中可能有什么问题?

下面是我的程序

public static List<String> wrapText(String text, float maxWidth,
Graphics2D g, Font displayFont) {
// Normalize the graphics context so that 1 point is exactly
// 1/72 inch and thus fonts will display at the correct sizes:
GraphicsConfiguration gc = g.getDeviceConfiguration();
g.transform(gc.getNormalizingTransform());

AttributedCharacterIterator paragraph = new AttributedString(text).getIterator();
Font backupFont = g.getFont();
g.setFont(displayFont);
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(
paragraph, BreakIterator.getWordInstance(), g.getFontRenderContext());
// Set position to the index of the first character in the paragraph.
lineMeasurer.setPosition(paragraph.getBeginIndex());

List<String> lines = new ArrayList<String>();
int beginIndex = 0;
// Get lines until the entire paragraph has been displayed.
while (lineMeasurer.getPosition() < paragraph.getEndIndex()) {
lineMeasurer.nextLayout(maxWidth);
lines.add(text.substring(beginIndex, lineMeasurer.getPosition()));
beginIndex = lineMeasurer.getPosition();
}

g.setFont(backupFont);
return lines;
}

public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane txtp = new JTextPane();
frame.add(txtp);
frame.setSize(200,200);
frame.setVisible(true);
Font displayFont = new Font("Times New Roman", Font.PLAIN, 14);

float textWith = (179 * 0.0393701f) // from Millimeter to Inch
* 72f; // From Inch to Pixel (User space)
List<String> lines = wrapText(
"Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vstrt vsip d asfd eacc",
textWith,
(Graphics2D) txtp.getGraphics(),
displayFont);
for (int i = 0; i < lines.size(); i++) {
System.out.print("Line " + (i + 1) + ": ");
System.out.println(lines.get(i));
}
frame.dispose();
}

最佳答案

问题+1

根据我使用文本编辑器的经验,不可能实现完全相同的测量。

您可以尝试使用 DPI,在 Windows 上默认 DPI=72 和 96。

您还可以尝试使用图形的所有渲染提示 - 文本抗锯齿等。

关于java - LineBreakMeasurer 产生的结果不同于 MS Word/LibreOffice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15698821/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com