Code Hungry
Code Hungry

Reputation: 4000

Specify line spacing while appending text on Image

I am Appending Text on images. How to specify the Line spacing between two lines while appending on the text on the image?

EDIT:- I want to Control Line Height of the text.

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

Upvotes: 0

Views: 1105

Answers (2)

Code Hungry
Code Hungry

Reputation: 4000

Now I am Passing value for lineHeight instead of 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;
            }
    }

Upvotes: 2

Jan Krakora
Jan Krakora

Reputation: 2610

If a bigger y as @Andrew Thompson post in comment isn't enough flexible for you. This is what you are looking for http://docs.oracle.com/javase/tutorial/2d/text/drawmulstring.html

Upvotes: 1

Related Questions