全理由与Java Graphics.drawString更换?全理由与Java Graphics.d

2019-05-12 03:01发布

有谁知道现有的代码,可以让你在Java2D的画完全有道理的文字?

例如,如果我说, drawString("sample text here", x, y, width) ,是有可能弄清楚如何使文本的多适合宽度内,做一些跨字符间距,使现有的库文字看起来不错,并自动执行基本的自动换行?

Answer 1:

虽然不是最优雅的,也没有强大的解决方案,这里是一个将采取的方法Font当前的Graphics对象并获取它FontMetrics以找出绘制文本,如有必要,移动到新行:

public void drawString(Graphics g, String s, int x, int y, int width)
{
    // FontMetrics gives us information about the width,
    // height, etc. of the current Graphics object's Font.
    FontMetrics fm = g.getFontMetrics();

    int lineHeight = fm.getHeight();

    int curX = x;
    int curY = y;

    String[] words = s.split(" ");

    for (String word : words)
    {
        // Find out thw width of the word.
        int wordWidth = fm.stringWidth(word + " ");

        // If text exceeds the width, then move to next line.
        if (curX + wordWidth >= x + width)
        {
            curY += lineHeight;
            curX = x;
        }

        g.drawString(word, curX, curY);

        // Move over to the right for next word.
        curX += wordWidth;
    }
}

此实现将指定的分隔String到数组String使用split方法用空格字符作为唯一的字分离器,所以它可能不是非常稳健。 它还假定字后跟一个空格字符和移动时相应地动作curX位置。

我不建议使用此实现,如果我是你,但可能是需要为了使另一个实现将仍然使用由提供的方法的功能FontMetrics类 。



Answer 2:

对于自动换行,你可能会感兴趣如何输出上使用图形多行字符串 。 这里没有任何理由,不知道这是否是容易的(或不可能的!)加...



文章来源: Full-justification with a Java Graphics.drawString replacement?