2

Swing アプリケーションでは、文字列を MS Word や LibreOffice などのワード プロセッサ プログラムに入れるときのように、文字列のテキスト ラッピングを予測する必要があります。次のように、同じ幅の表示可能領域、同じフォント (書体とサイズ)、および同じ文字列を提供します。

  • 表示可能領域の幅: 179mm (.doc ファイルで、A4 縦長のページを設定します - 幅 = 210mm、マージン左 = 20mm、右 = 11mm; 段落はゼロ マージンでフォーマットされます)
  • フォント Times New Roman、サイズ 14
  • テスト文字列: Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vstrt vsip d asfd eacc

そして結果:

  • MS Word と LibreOffice の両方で、そのテスト文字列は 1 行で表示され、テキストの折り返しは発生しません。
  • 私の次のプログラムは、テキストの折り返しが発生したことを報告します.2行

    1 行目: Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vstrt 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();
}
4

1 に答える 1

2

質問に+1

私のテキスト エディターでの経験からすると、まったく同じ測定を行うことはできません。

WindowsではデフォルトのDPI = 72および96であるDPIで遊ぶことができます。

また、グラフィックスのすべてのレンダリング ヒント (テキスト アンチエイリアシングなど) を試してみることもできます。

于 2013-03-29T07:33:08.283 に答える