2011-01-25 63 views
0

我需要打印兩個詞 「」 和 「」 用java 2D如何獲得java2D中的Font X偏移寬度?

字體大小= 100;

一個」 字體家族:波多尼MT海報壓縮

」 字體family:宋體

我所著下面的代碼做到這一點:

BufferedImage image = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB); 
Graphics g = image.getGraphics(); 
{//fill bg color 
    g.setColor(new Color(255,255,255)); 
    g.fillRect(0, 0, image.getWidth(), image.getHeight()); 
}   

int FONT_SIZE=100;//set font size 
{//print A 
    g.setColor(new Color(0,0,0)); 
    g.setFont(new Font("Bodoni MT Poster Compressed", Font.PLAIN ,FONT_SIZE));  
    g.drawString("A",0,FONT_SIZE); 
} 
{//print B 
    g.setColor(new Color(0,0,0)); 
    g.setFont(new Font("Arial", Font.PLAIN ,FONT_SIZE));   
    g.drawString("B",FONT_SIZE,FONT_SIZE); 
} 
g.dispose(); 

我得到結果圖片:enter image description here

但我需要這樣(Photoshop所製作):enter image description here

我認爲g.drawString("B",FONT_SIZE,FONT_SIZE);

我怎樣才能獲得字體的X軸偏移寬度的問題?

感謝幫助:)

回答

1

後你做時setfont,申報像

FontMetrics fm = g.getFontMetrics(); 
int strA = fm.stringWidth("A"), 
    strB = fm.stringWidth("B"), 
    strH = fm.getHeight(); 

變量現在,你有字母的所有尺寸,設置它們的位置(PX是從距離左邊緣到字母,py從頂部到字體的基線)

int px = ..., py = ... 
g.drawString ("A", px, py); 

對於「B」類似。希望有所幫助, - M.S.

+0

謝謝!這是完美的! – Koerr 2011-01-25 04:31:46