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和各種渲染提示,但沒有運氣。看來我們必須接受近似的測量。 –