-2

I am trying to create images at runtime using graphics class. But though I have a string like line 1 \n line 2, I get the text written on the image as a single line.

Can anyone help me on this front with an example?

  • 1
    Your question is unclear. Try to clarify what you want to do and the relevant code – jhamon Mar 06 '19 at 08:19
  • Possible duplicate of [Write multi line text on an image using Java](https://stackoverflow.com/questions/32110247/write-multi-line-text-on-an-image-using-java) – Arnaud Mar 06 '19 at 08:22
  • If you want someone to help you with the problem in your code you need to start with posting your code (see [mcve]) – Erwin Bolwidt Mar 06 '19 at 08:28

1 Answers1

0

To remove the line breaks from your string, you can use the following method:

String str = "Line 1\nLine 2";
str.replace(System.getProperty("line.separator"), "");

You can use the BufferedImage class for creating the image:

// Create the target Font and a FontMetrics object for measuring the string's dimensions on the canvas
Font font = new Font("Helvetica", Font.PLAIN, 12);
FontMetrics fm = new Canvas().getFontMetrics(font);

// Create a BufferedImage and obtain the Graphics object
BufferedImage img = new BufferedImage(fm.stringWidth(str), fm.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();

// Draw the string at position (0|0)
g.setColor(Color.black);
g.drawString(str, 0, 0);
kske
  • 128
  • 1
  • 3
  • 8