2014-01-21 2 views
4

Java의 drawString(String str, int x, int y) 메소드를 알고 있습니다. 그러나 때로는 글꼴 크기 (pts 또는 원의 크기에 따라)가 주어지면 중간에 적절한 문자열이있는 원을 표시하는 것이 좋습니다. 그것을 할 수있는 쉬운 방법이 있습니까? 아니면 혼자서 수학을 만들어야합니까? 그렇다면 글꼴 크기 (int pts)의 함수로 문자열의 폭을 계산하는 방법은 무엇입니까?원에 새겨진 문자 그리기

+4

정말 쉬운 방법이 아니다. [글꼴 메트릭스] (http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html) –

+2

[텍스트 측정] (http://docs.oracle.com/javase/tutorial/2d/) text/measuringtext.html)이 시작일 수 있습니다. – asgs

+0

나는 보통 ['GlyphVector'] (http://stackoverflow.com/a/6296381/418556)를 사용하지만이 고양이를 다듬는 데는 12 가지 방법이 있어야합니다. –

답변

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. 
} 

}