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?
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?
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);