我正在寻找一种简单的方法将字符串渲染为JPG中的矩形框,而换行符应该自动发生在该文本框中。
这可以用Graphics2D
吗?
在单行上渲染字符串很简单,以下代码片段使用Antialiasing以及良好的JPG输出压缩质量:
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.");
答案 0 :(得分:3)
结帐LineBreakMeasurer
。 API有一些示例代码可以帮助您入门。
或者另一种方法是使用您的图像创建JLabel。然后,您可以将JTextArea添加到标签并设置包装属性。然后,当您将文本区域添加到标签时,文本将自动换行。您将手动需要设置标签内文本区域的边界以控制文本的位置。