用 Java Graphics.drawString 替换的完全理由? [英] Full-justification with a Java Graphics.drawString replacement?

查看:18
本文介绍了用 Java Graphics.drawString 替换的完全理由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道可以让您在 Java2D 中绘制完全对齐的文本的现有代码?

Does anyone know of existing code that lets you draw fully justified text in Java2D?

例如,如果我说,drawString("sample text here", x, y, width),是否有一个现有的库可以计算出该文本有多少适合宽度, 做一些字符间距让文字好看,自动做基本自动换行?

For example, if I said, drawString("sample text here", x, y, width), is there an existing library that could figure out how much of that text fits within the width, do some inter-character spacing to make the text look good, and automatically do basic word wrapping?

推荐答案

虽然不是最优雅、最健壮的解决方案,但这里有一种方法可以采用 Font 当前Graphics 对象并获取其FontMetrics 以找出绘制文本的位置,如果必要,移到新行:

Although not the most elegant nor robust solution, here's an method that will take the Font of the current Graphics object and obtain its FontMetrics in order to find out where to draw the text, and if necessary, move to a new line:

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;
    }
}

此实现将使用 split 方法,以空格字符作为唯一的单词分隔符,所以它可能不是很健壮.它还假定单词后跟一个空格字符并在移动 curX 位置时相应地进行操作.

This implementation will separate the given String into an array of String by using the split method with a space character as the only word separator, so it's probably not very robust. It also assumes that the word is followed by a space character and acts accordingly when moving the curX position.

如果我是你的话,我不会推荐使用这个实现,但是为了进行另一个实现所需的函数可能仍然会使用 FontMetrics.

I wouldn't recommend using this implementation if I were you, but probably the functions that are needed in order to make another implementation would still use the methods provided by the FontMetrics class.

这篇关于用 Java Graphics.drawString 替换的完全理由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆