2012-01-17 85 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版本具有与此相关的附加功能。

相关问题