根据特定字体中文本的显示宽度留出空间

时间:2014-10-15 20:58:13

标签: java bufferedimage

我创建了一个应用程序,它可以读取文本文件中的所有行,并使用ttf字体在BufferedImage上写入该文本。这里,BufferedImage只是笔记本中空的统治页面的图像。我试图从文件中读取内容并将其写在BufferedImage(即纸张的图像)上。我能够做到。但是我遇到了一些问题,比如有些单词会重叠。这是我到目前为止写入BufferedImage的代码。

private void printText()
{       
    x = leftSpacing;  // leftSpacing - The amount of space to be left blank from the left side(i.e, to leave the area of the paper where we write the question number and answer number).
    y = upSpacing;    // upSpacing - The amount of space to be left blank from the top of the paper(i.e, to leave the part of the paper where we write the date and page number). 
    /*

    words - ArrayList<ArrayList<String>>,
                    in which each array list contains each line of the file. 
                    like words(1) contains all words of first line,
                         words(2) contains words of second line, and so on. 
    */

    for(ArrayList<String> listOfWords : words)
    { // Iterate through each sentence
        for(String word : listOfWords)
        {   // Iterate through each word of the sentence
            textContainer = font.getStringBounds(word+" ", context);  // Get bounds of the word along with a space in the form of java.awt.Rectangle2D
            x += textContainer.getWidth();  // Add width of the word to the X co-ordinate.

            // Test if X has become greater than imageWidth - space left from left side.
            if(x > imageWidth - leftSpace)
            { 
                x = leftSpacing;  // Set X back to 0
                y += lineSpacing; // And move Y to next line. lineSpacing - Anount of gap to be left between printing each line.
            }

            if(y > imageHeight)
            {  // If Y is more than imageHeight
                return;  // Simply quit printing and return
            }

            graphics.drawString(word+" ", x, y);  // Draw word at X, Y
        }
    }
}  

任何帮助将不胜感激。谢谢你提前。

0 个答案:

没有答案