2014-01-21 46 views
4

我知道Java的drawString(String str, int x, int y)方法;然而,有時候我想要的只是在給定字體大小的情況下(在pts中或根據圓的大小)在中間用適當的字符串標記一個圓。有沒有簡單的方法來做到這一點,還是必須自己做數學?如果是這樣,一個字符串的寬度如何計算,作爲字體大小(int pts)的函數?繪製字符串刻在一個圓圈內

+4

有沒有真正的捷徑。使用[Font Metrics](http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html) –

+2

[Measuring Text](http://docs.oracle.com/javase/tutorial/2d/) text/measuringtext.html)可能是一個開始。 – asgs

+0

我通常使用['GlyphVector'](http://stackoverflow.com/a/6296381/418556),但必須有十幾種方法來剝皮這隻貓。 –

回答

0

下面是一個例子。文字繪圖是Software Monkey列出的答案的修改版本,用於使用給定的座標,而不是繪製在組件的中心。

如果您想繪製一個未覆蓋整個組件的圓,那麼您必須計算圓的中心,並將其傳遞到drawCenteredText

Random類的業務是爲了演示這種方法如何處理任何字體大小。

public class LabledCircle { 

public static void main(String args[]) { 
JFrame frame = new JFrame(); 

// Create and add our demo JPanel 
// I'm using an anonymous inner class here for simplicity, the paintComponent() method could be implemented anywhere 
frame.add(new JPanel() { 
    public void paintComponent(Graphics g) { 
    super.paintComponent(g); 

    // Draw a circle filling the entire JPanel 
    g.drawOval(0, 0, getWidth(), getHeight()); 

    Random rad = new Random();// For generating a random font size 

    // Draw some text in the middle of the circle 
    // The location passed here is the center of where you want the text drawn 
    drawCenteredText(g, getWidth()/2, getHeight()/2, rad.nextFloat() * 30f, "Hello World!"); 
    } 
}); 

frame.setSize(200, 200); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.setVisible(true); 
} 

public static void drawCenteredText(Graphics g, int x, int y, float size, String text) { 
// Create a new font with the desired size 
Font newFont = g.getFont().deriveFont(size); 
g.setFont(newFont); 
// Find the size of string s in font f in the current Graphics context g. 
FontMetrics fm = g.getFontMetrics(); 
java.awt.geom.Rectangle2D rect = fm.getStringBounds(text, g); 

int textHeight = (int) (rect.getHeight()); 
int textWidth = (int) (rect.getWidth()); 

// Find the top left and right corner 
int cornerX = x - (textWidth/2); 
int cornerY = y - (textHeight/2) + fm.getAscent(); 

g.drawString(text, cornerX, cornerY); // Draw the string. 
} 

}