我試圖做一個方法,將給定的String
(和Font
)轉換爲BufferedImage
。但是,每次運行它時,都會返回完全黑色的圖像。圖像的確切大小似乎是正確的,但所有像素都是完全黑色的。爲什麼我的文本到圖像方法返回全黑圖像?
下面的代碼:
static final GraphicsEnvironment GE;
static
{
GE = GraphicsEnvironment.getLocalGraphicsEnvironment();
}
public static BufferedImage textToImage(String text, Font font)
{
if (font == null)
font = Font.getFont("Courier New");
FontRenderContext frc = new FontRenderContext(new AffineTransform(), false, false);
Rectangle2D bounds = font.getStringBounds(text, frc);
BufferedImage bi = new BufferedImage(
(int)(bounds.getWidth() + .5),
(int)(bounds.getHeight() + .5),
BufferedImage.TYPE_BYTE_BINARY
);
Graphics2D g = GE.createGraphics(bi);
g.setFont(font);
g.drawString(text, 0, 0);
return bi;
}
這裏的「Hello World」的中顯示爲JOptionPane
的圖標默認JOptionPane
字體:
@MadProgrammer哦廢話XD對不起,我完全打算把代碼放進去。對不起,我必須比我更累。一會兒。 – Supuhstar 2014-12-08 04:07:44
@MadProgrammer好吧,代碼添加。對不起,^^; – Supuhstar 2014-12-08 04:08:33