2011-11-24 51 views
0

我正在尋找一種簡單的方法來將字符串呈現爲JPG內的矩形框,而換行符應該自動爲該文本框發生。Java 1.6 Graphics2D:將文本渲染到一個框中

這可能與Graphics2D

呈現在一行的字符串是容易的,下面的代碼段使用抗鋸齒以及良好的輸出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."); 

回答

3

退房LineBreakMeasurer。該API有一些示例代碼來幫助您入門。

或者另一種方法是用你的圖像創建一個JLabel。然後你可以添加一個JTextArea到標籤並設置包裝屬性。然後,將文本區域添加到標籤時,文本將自動換行。您將手動設置標籤內文本區域的邊界以控制文本的位置。

+0

非常感謝! JTextArea解決了它。 – basZero