2014-12-08 27 views
0

我試圖做一個方法,將給定的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字體: A Windows dialog titled "Hello World", containing only a small, black rectangle.

+1

@MadProgrammer哦廢話XD對不起,我完全打算把代碼放進去。對不起,我必須比我更累。一會兒。 – Supuhstar 2014-12-08 04:07:44

+0

@MadProgrammer好吧,代碼添加。對不起,^^; – Supuhstar 2014-12-08 04:08:33

回答

1

簡單的解決辦法是改變顏色..

g.setColor(Color.WHITE); 
    g.fillRect(0, 0, bi.getWidth(), bi.getHeight()); 
    g.setColor(Color.BLACK); 
    g.setFont(font); 
    g.drawString(text, 0, 0); 
    g.dispose(); 

文本一般不會從y位置呈現do WN,它得出的向上和向下從y位置,所以你需要使用像......

FontMetrics fm = g.getFontMetrics(); 
    g.drawString(text, 0, fm.getAscent()); 

來獲取文本正常顯示...

而且font = Font.getFont("Courier New");不按照你的想法,這將不會返回名爲"Courier New"的字體,而是嘗試加載名爲"Courier New"的字體文件。

嘗試使用類似...

if (font == null) { 
     font = new Font("Courier New", Font.PLAIN, 12); 
    } 

,而不是...

你可能想仔細看看Working with Text APIs更多細節

+0

謝謝,完美的工作! – Supuhstar 2014-12-08 04:42:47

+0

很高興幫助... – MadProgrammer 2014-12-08 04:43:19

相關問題