java - 在图像上附加文本时指定行距

标签 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;
        }
}

最佳答案

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

关于java - 在图像上附加文本时指定行距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13861075/

相关文章:

java - java主机上的堆空间

java - 准备响应主体的逻辑应该在@Service还是@Controller上?

php - 图像大小调整不起作用(使用 base64)

image - 如何在 ASP 更新面板中使用 telerik RadAsyncUpload 和 RadBinaryImage 预览上传的图像?

java - Swing 和 AWT : ContentPane items not showing in JFrame

java - 在 Java2D AWT 框架中使用世界坐标

Java:光标如何自动从一个 TextField 移动到另一个

java - 如何自定义实现 Retrofit2.Call<T>

java - 跨多个线程的任务的日志关联

核心图形: Encode RGBA data to PNG