我正在尝试将一些样式化的文本绘制到缓冲图像中。我使用不属于任何视图层次结构的 JTextPane。我将文档属性设置为所需的对齐方式,但结果未正确对齐。更糟糕的是,当再次运行相同的测试时,我会得到不同字体大小的不同结果,有时甚至会得到不同的结果。
下图显示了结果。段落应该是,从上到下,左对齐,居中,右对齐,完整。红框是 JTextPane 边框。你自己看。
因为我是新的 stackoverflow 用户,所以它不允许我发布图片。您可以在http://www.sendtoprint.net/preview/textfile.jpg看到图像
这是在 Java 1.7 上完成的,但也发生在 1.6 中。编码:
public void createBufferedImage ()
{
try
{
BufferedImage bi = new BufferedImage (1000, 1200, BufferedImage.TYPE_INT_RGB);
Graphics2D gg = bi.createGraphics ();
gg.setRenderingHint (RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gg.setRenderingHint (RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
gg.setBackground (Color.white);
gg.fillRect (0, 0, bi.getWidth (), bi.getHeight ());
gg.scale (3.0f, 3.0f);
gg.translate (16, 16);
String text = "The residents of Colorado and Washington state have voted to legalize "
+ "the recreational use of marijuana, and all hell is about to break "
+ "loose -- at least ideologically. The problem is that pot is still very much "
+ "illegal under federal law, and the Obama administration must decide whether "
+ "to enforce federal law in a state that has rejected the substance of that law."
+ "\n\n";
DefaultStyledDocument doc = new DefaultStyledDocument ();
MutableAttributeSet attr = new SimpleAttributeSet ();
StyleConstants.setFontFamily (attr, "Arial");
StyleConstants.setFontSize (attr, 9);
StyleConstants.setForeground (attr, Color.black);
MutableAttributeSet parAttr = new SimpleAttributeSet ();
doc.insertString (0, text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_LEFT);
doc.setParagraphAttributes (0, doc.getLength (), parAttr, false);
doc.insertString (doc.getLength (), text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes (doc.getLength () - text.length (), text.length (), parAttr, false);
doc.insertString (doc.getLength (), text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_RIGHT);
doc.setParagraphAttributes (doc.getLength () - text.length (), text.length (), parAttr, false);
doc.insertString (doc.getLength (), text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_JUSTIFIED);
doc.setParagraphAttributes (doc.getLength () - text.length (), text.length (), parAttr, false);
JTextPane tc = new JTextPane ();
tc.setBorder (BorderFactory.createLineBorder (Color.red, 1));
tc.setDocument (doc);
tc.setBackground (Color.white);
tc.setLocation (0, 0);
tc.setSize (new Dimension (300, 370));
tc.paint (gg);
System.out.println ("Writing file: " + new Date ().toString ());
File file = new File ("C:\\Users\\Yishai\\Desktop\\text\\file.jpg");
ImageIO.write (bi, "jpg", file);
}
catch (Exception e)
{
System.out.println (e.getMessage ());
}
}
有什么想法我可以做些什么不同的事情吗?有 JTextPane 设置吗?文本缓存?任何事物?
谢谢。