0

在图像上附加文本。如何在附加到图像上的文本时指定两行之间的行距?

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

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

2 回答 2

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;
            }
    }
于 2012-12-14T07:41:28.357 回答
1

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

于 2012-12-13T15:46:34.330 回答