【问题标题】:Specify line spacing while appending text on Image在图像上附加文本时指定行距
【发布时间】:2012-12-01 09:58:10
【问题描述】:

我是Appending Text on images。在图片上追加文字时如何指定两行之间的行距?

编辑:-我想控制文本的行高。

final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
java.awt.Font a=new java.awt.Font("AndaleWTJ", java.awt.Font.PLAIN, 26);
g.setFont(a);
g.setColor(Color.RED);
FontMetrics fm = g.getFontMetrics();
drawString(g,Title,15, 84,402,199,171,1);
g.dispose();

public static void drawString(Graphics g, String s, int x, int y, int width,int red_val,int green_val, int blue_val)
{     FontMetrics fm = g.getFontMetrics();
      java.awt.Color c= new java.awt.Color(red_val, green_val, blue_val);
      g.setColor(c);
      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;
        }
}

【问题讨论】:

  • ..为drawString(..) 使用更大的y 偏移量。如果这不能回答问题,请发布SSCCE
  • 现在发布您用于在图像上输出线条的代码。评论如何解决它比不举例说明更容易。

标签: java image awt java-2d


【解决方案1】:

现在我正在传递 lineHeight 的值,而不是 int lineHeight = fm.getHeight();

 public static void drawString(Graphics g, String s, int x, int y, int width,int red_val,int green_val, int blue_val, int lineHeight )
    {     FontMetrics fm = g.getFontMetrics();
          java.awt.Color c= new java.awt.Color(red_val, green_val, blue_val);
          g.setColor(c);
          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;
            }
    }

【讨论】:

  • 这应该是一个答案,还是问题的扩展?如果不是答案,请将其编辑到问题中。
  • @AndrewThompson :- 这就是答案。现在我可以根据我的要求调整 lineHeight 了。感谢您的宝贵反馈
【解决方案2】:

如果@Andrew Thompson 在评论中发布的更大 y 对您来说不够灵活。这就是你要找的http://docs.oracle.com/javase/tutorial/2d/text/drawmulstring.html

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 1970-01-01
    • 2012-12-08
    • 2013-10-27
    • 2012-06-20
    • 2022-01-16
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多