1

重複の可能性:
Graphics2D.drawString の改行に関する問題

String eol =System.lineSeparator();  
        String sampleText =epcURNText +eol+studentName+eol+DelayComments+eol+ArrivalMethodComments+eol;
        System.out.println(sampleText);
        Font font = new Font("Tahoma", Font.PLAIN, 11);
        FontRenderContext frc = new FontRenderContext(null, true, true);

        //get the height and width of the text
        Rectangle2D bounds = font.getStringBounds(sampleText, frc);
        int w = (int) bounds.getWidth();
        int h = (int) bounds.getHeight();

        //create a BufferedImage object
        BufferedImage image = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_RGB);

        //calling createGraphics() to get the Graphics2D
        Graphics2D g = image.createGraphics();

        //set color and other parameters
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, w, h);
        g.setColor(Color.BLACK);
        g.setFont(font);

        g.drawString(sampleText, (float) bounds.getX(),
                (float) -bounds.getY());

        //releasing resources
        g.dispose();



        // define the format of print document
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "gif", os);
        File f = new File("MyFile.jpg");
        ImageIO.write(image, "JPEG", f);

前述のコード内で、画像内に改行文字を含む文字列を出力しようとしています。ただし、改行文字が省略されているため、テキストは 1 行で表示されますか? これを修正する方法について誰か考えがありますか?

4

1 に答える 1

2

この回答のソースにJLabel示されているように、テキストを HTML 形式でレンダリングします。 LabelRenderTest

改行よりも優れたもの、つまりボディ幅のスタイルを提供します。テキストの改行を配置する場所を手動で計算する必要がないという意味で優れています (固定幅ではないフォントでレンダリングされる場合もあります)。

于 2012-11-01T11:55:09.630 に答える