2011-03-30 5 views
0

有人可以檢查我的語法嗎?我通過「Times New Roman」,「Arial」,「Verdana」到fontName,並使用8,12,15等來獲得fontSize。它從不改變這裏的字體。我這樣做是爲了在圖像上寫一些文字。在Java中更改字體和繪製字符串的正確語法是什麼?

Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics(); 
g2d.drawImage(photo, 0, 0, null); 
g2d.setColor(Color.white); 
Font font = new Font(fontName, Font.PLAIN, fontSize); 
g2d.setFont(font); 
g2d.drawString(text,x,y); 

回答

2

我終於發現,我的列表中沒有任何字體在系統上,所以我不得不使用getAllFonts()方法,並只傳遞列表中的字體。

0

你應該做的事,從Sun文檔此

BufferedImage img = new BufferedImage(
    w, h, BufferedImage.TYPE_INT_ARGB); 
Graphics2D g2d = img.createGraphics(); 
g2d.drawImage(photo, 0, 0, null); 
g2d.setPaint(Color.red); 
//example :  g2d.setFont(new Font("Serif", Font.BOLD, 15)); 
g2d.setFont(new Font(fontName, Font.BOLD, size)); 
String s = "Hello, world!"; 
// assuming x & y is set using graphic's font metrics 
g2d.drawString(s, x, y); 
g2d.dispose(); 

摘錄

的getGraphics

公共圖形的getGraphics()此 方法返回Graphics2D,但 這裏爲了向後兼容。 createGraphics更方便, ,因爲它聲明返回一個 Graphics2D。

這並不意味着您不應該使用getGraphics API。只是上面的代碼爲我工作:)

相關問題