2
在一个swing应用程序中,我需要预见字符串的文本包装,就像将它放入文字处理程序(如MS Word或LibreOffice)中一样。提供了可显示区域的宽度相同,相同的字体(面部和尺寸)和相同的字符串如下:LineBreakMeasurer产生的结果与MS Word/LibreOffice不同
- 显示区域宽度:179毫米(在.doc文件,设置一个A4纵向页 - 宽度= 210毫米,距左=20毫米,右=11毫米;段落的格式与零页边距)
- 字体Times New Roman字体,大小为14
- 测试字符串:TADF FDAS FDAS daebjnbvx dasf opqwe DSA:DFA FDSA ewqnbcmv caqw vstrt VSIP d asfd eacc
而结果:
- 在MS Word和LibreOffice上,该测试字符串显示在单行上,不会发生文本换行。
我的波纹管程序报告文字环绕发生时,2行
第1行:TADF FDAS FDAS daebjnbvx dasf opqwe DSA:DFA FDSA ewqnbcmv caqw vstrt VSIP d ASFD
第2行:EACC
是否有可能实现像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();
}
我必须承认,获得确切的结果是不可能的。我试图玩DPI和各种渲染提示,但没有运气。看来我们必须接受近似的测量。 –