2012-01-17 87 views
0

我的目標是在圖像上追加文本並保存圖像。我可以在圖像上添加文字。 我的問題是如何指定區域對於文本,以及如何使其成爲多行,以便數據不會跨越邊界。 代碼: -在圖像上添加多行文本並將其保存

public Test() 
{ 
s = "Welcome TO Image Rendering"; 
s1="Title data"; 
s2="DescriptionA fast paced action thriller about a stunt driver.He finds himself a target for some dangerous men after he agrees to help his beautiful neighbour, Irene. Subtitles: Chinesedata"; 
     Font f = new Font("Serif",Font.BOLD,22); 
     text = new JLabel("Welcome TO Image Rendering"); 
     text.setFont(f); 

     AttributedString astr = new AttributedString(s); 
     astr.addAttribute(TextAttribute.FOREGROUND, Color.red, 0, 1); 

     MediaTracker mt = new MediaTracker(this); 
     image = Toolkit.getDefaultToolkit().createImage("c://Ci_Audio.jpg"); 
     mt.addImage(image,0); 
     try{mt.waitForID(0);}catch(InterruptedException ie){} 
     int width = image.getWidth(null); 
     int height = image.getHeight(null); 
     BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
     bimg.createGraphics().drawImage(image, 0, 0, this); 
     bimg.getGraphics().setFont(f); 
     bimg.getGraphics().drawString(s,10,50); 
     bimg.getGraphics().drawString(s1,38,40); 
     bimg.getGraphics().drawString(s2,188,84); 
     img = new ImageIcon(bimg); 
     label = new JLabel(img); 
     p = new JPanel(); 
     p.add(label); 
     getContentPane().add(p); 
    } 
    public static void main(String args[]) 
     { 
     Test tt = new Test(); 
     tt.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     tt.setSize(360,305); 
     tt.setVisible(true); 
    } 
} 

這裏串S將不適合的影像畫面。提前致謝。

回答

0

在設置了您打算使用的字體後,您可以調用當前Graphics上的getFontMetrics()。 FontMetrics.stringWidth(your_string)會給你當前字體的字符串寬度,就像你的BufferedImage中顯示的那樣。然後您可以建立字符串,直到它超過圖像的寬度,然後爲下一行開始另一個字符串。一旦將字符串拆分並知道需要包含多少行/字符串,就必須找出字符串位置的垂直偏移量。這次再次使用fontMetrics來計算字符串高度。

這裏有一個類似的問題,讓分裂的一個簡單的版本:

Full-justification with a Java Graphics.drawString replacement?

這裏有一個實用工具類,做了很多這樣的工作,爲您提供的FontMetrics對象和字符串 http://www.java2s.com/Code/Java/2D-Graphics-GUI/WrapstringaccordingtoFontMetrics.htm

有人其他人可以評論我相信如果更新的Java版本具有與此相關的附加功能。

相關問題