有没有人知道现有代码可以让你在
Java2D中绘制完全对齐的文本?
例如,如果我说,drawString(“这里的示例文本”,x,y,宽度),是否有一个现有的库可以找出该文本中有多少适合宽度,做一些字符间间距来做文字好看,并自动做基本的自动换行?
解决方法
虽然不是最优雅也不是最强大的解决方案,但这里有一个方法,它将获取当前
Graphics
对象的
Font
并获取其
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;
- }
- }
此实现将使用split
方法将给定的String分隔为String数组,并将空格字符作为唯一的单词分隔符,因此它可能不是很健壮.它还假定该单词后跟空格字符,并在移动curX位置时相应地起作用.
如果我是你,我不建议使用这个实现,但是为了进行另一个实现,可能还需要使用FontMetrics
class提供的方法.