在Image上附加文本时指定行间距

时间:2012-12-13 13:41:04

标签: java image awt java-2d

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

2 个答案:

答案 0 :(得分:2)

现在我传递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;
            }
    }

答案 1 :(得分:1)

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