Search code examples
javaswinggraphicsgraphics2d

Java 1.6 Graphics2D: Rendering text into a box


I am looking for an easy way to render a String into a rectangular box within a JPG whereas line breaks should happen automatically for that text box.

Is this possible with Graphics2D ?

Rendering a string on a single line is easy, the following code snippet uses Antialiasing as well as a good JPG output compression quality:

BufferedImage img = ImageIO.read(new File(".../input.jpg"));
int width = img.getWidth();
int height = img.getHeight();

Color zgColor = new Color(0xAB,0x3C,0x2E);
Color grey = new Color(0xCC,0xCC,0xCC);

BufferedImage bufferedImage = new BufferedImage(width, height, img.getType());
Graphics2D g = bufferedImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// draw graphics
g.drawImage(img, 0, 0, null);
g.setColor(zgColor);
int y = 900;
int x = 50;
g.setFont(new Font("Arial", Font.BOLD, 80));
g.drawString("Demo Text", x, y);

y+=80;
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 60));
g.drawString("Some other text a bit below", x, y);

y+=400;
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
g.drawString("AND THIS WOULD BE THE TEXT I'D LIKE TO FIT INTO A BOX WITH AUTOMATIC LINE BREAKS", x, y);

g.dispose();

// Save as high quality JPEG
File targetFile = new File(".......result.jpg");
//ImageIO.write(bufferedImage, "jpg", targetFile); // this would give bad quality!

Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1); // best quality
FileImageOutputStream output = new FileImageOutputStream(targetFile);
writer.setOutput(output);
IIOImage image = new IIOImage(bufferedImage, null, null);
writer.write(null, image, iwp);
writer.dispose();            
System.out.println("Done.");

Solution

  • Check out LineBreakMeasurer. The API has some example code to get you started.

    Or another approach is to create a JLabel with your image. Then you can add a JTextArea to the label and set the wrapping property on. Then the text will automatically wrap when you add the text area to the label. You will manually need to set the bounds of the text area within the label to control the placement of the text.