使用Java Graphics.drawString替换完全合理化?

前端之家收集整理的这篇文章主要介绍了使用Java Graphics.drawString替换完全合理化?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有人知道现有代码可以让你在 Java2D中绘制完全对齐的文本?

例如,如果我说,drawString(“这里的示例文本”,x,y,宽度),是否有一个现有的库可以找出该文本中有多少适合宽度,做一些字符间间距来做文字好看,并自动做基本的自动换行?

解决方法

虽然不是最优雅也不是最强大的解决方案,但这里有一个方法,它将获取当前 Graphics对象的 Font获取FontMetrics,以便找出绘制文本的位置,并在必要时移动到新行:
  1. public void drawString(Graphics g,String s,int x,int y,int width)
  2. {
  3. // FontMetrics gives us information about the width,// height,etc. of the current Graphics object's Font.
  4. FontMetrics fm = g.getFontMetrics();
  5.  
  6. int lineHeight = fm.getHeight();
  7.  
  8. int curX = x;
  9. int curY = y;
  10.  
  11. String[] words = s.split(" ");
  12.  
  13. for (String word : words)
  14. {
  15. // Find out thw width of the word.
  16. int wordWidth = fm.stringWidth(word + " ");
  17.  
  18. // If text exceeds the width,then move to next line.
  19. if (curX + wordWidth >= x + width)
  20. {
  21. curY += lineHeight;
  22. curX = x;
  23. }
  24.  
  25. g.drawString(word,curX,curY);
  26.  
  27. // Move over to the right for next word.
  28. curX += wordWidth;
  29. }
  30. }

此实现将使用split方法将给定的String分隔为String数组,并将空格字符作为唯一的单词分隔符,因此它可能不是很健壮.它还假定该单词后跟空格字符,并在移动curX位置时相应地起作用.

如果我是你,我不建议使用这个实现,但是为了进行另一个实现,可能还需要使用FontMetrics class提供的方法.

猜你在找的Java相关文章