2014-12-30 9 views
15

나는 현재 내 자바 게임 메뉴 시스템에서 일하고 있어요, 나는 내가 Graphics.drawString()에서 텍스트를 중심으로하는 방법을 궁금해 그래서 나는 그 중심점 X: 50Y: 50에있는 텍스트를 그리려하고있는 경우 텍스트가 30 픽셀이고 너비가 10 픽셀이면 X: 35Y: 45에서 텍스트가 시작됩니다.Java에서 Graphics.drawString()을 어떻게 배치 할 수 있습니까?

텍스트를 그리기 전에 텍스트의 너비를 결정할 수 있습니까?
그러면 수학이 쉬울 것입니다.

편집 : 텍스트의 높이를 가져올 수 있는지 궁금해서 텍스트를 세로로 가운데 놓을 수도 있습니다.

도움을 주시면 감사하겠습니다.

+2

이의 중복 것 같은데 : : http://stackoverflow.com/questions/258486/calculate-the-display-width-of-a-

내가 사용하는 코드는 다음과 같이 보입니다 string-in-java – mwarren

+0

이것은 Swing이 당신을 위해 일하는 것입니다. 이 답변을보십시오 : http://stackoverflow.com/questions/23729944/java-how-to-visually-center-a-specific-string-not-just-a-font-in-a-rectangle 게임을 작성하기 시작한 JavaFX는 Java 플랫폼에 포함 된 가장 최신 그래픽 툴킷이며 Swing보다 더 나은 선택 일 수 있습니다. – richj

+0

@mwarren 부분적으로는 복제본이지만 한 가지만 있습니다. 'FontMetrics.getHeight()/2'가 텍스트의 "진짜"높이의 절반을주지 않기 때문에 텍스트의 높이를 어떻게 얻을 수 있는지 궁금합니다. @richj , 그래서 나는 JavaFX로 전환하지 않을 것이라고 생각한다. 그것은 다른 게임을위한 것입니다. –

답변

34

나는 대답을 this question에 사용했다.

/** 
* Draw a String centered in the middle of a Rectangle. 
* 
* @param g The Graphics instance. 
* @param text The String to draw. 
* @param rect The Rectangle to center the text in. 
*/ 
public void drawCenteredString(Graphics g, String text, Rectangle rect, Font font) { 
    // Get the FontMetrics 
    FontMetrics metrics = g.getFontMetrics(font); 
    // Determine the X coordinate for the text 
    int x = rect.x + (rect.width - metrics.stringWidth(text))/2; 
    // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen) 
    int y = rect.y + ((rect.height - metrics.getHeight())/2) + metrics.getAscent(); 
    // Set the font 
    g.setFont(font); 
    // Draw the String 
    g.drawString(text, x, y); 
} 
+11

그래픽 g가 시스템에서 오는 경우이를 처리하면 안됩니다. –

+1

이 방법은 주어진 사각형의 x와 y를 사용하지 않습니다. 대신 int x = rect.x + (rect.width - metrics.stringWidth (text))/2;이어야합니다. int y = rect.y + ((rect.height-metrics.getHeight())/2) + metrics.getAscent(); –

+1

@IshanJain 좋은 지적, 나는 대답을 업데이트했다. –

2

텍스트를 그릴 때 일반적으로 텍스트를 경계 사각형에 가운데 맞춤해야합니다.

/** 
* This method centers a <code>String</code> in 
* a bounding <code>Rectangle</code>. 
* @param g - The <code>Graphics</code> instance. 
* @param r - The bounding <code>Rectangle</code>. 
* @param s - The <code>String</code> to center in the 
* bounding rectangle. 
* @param font - The display font of the <code>String</code> 
* 
* @see java.awt.Graphics 
* @see java.awt.Rectangle 
* @see java.lang.String 
*/ 
public void centerString(Graphics g, Rectangle r, String s, 
     Font font) { 
    FontRenderContext frc = 
      new FontRenderContext(null, true, true); 

    Rectangle2D r2D = font.getStringBounds(s, frc); 
    int rWidth = (int) Math.round(r2D.getWidth()); 
    int rHeight = (int) Math.round(r2D.getHeight()); 
    int rX = (int) Math.round(r2D.getX()); 
    int rY = (int) Math.round(r2D.getY()); 

    int a = (r.width/2) - (rWidth/2) - rX; 
    int b = (r.height/2) - (rHeight/2) - rY; 

    g.setFont(font); 
    g.drawString(s, r.x + a, r.y + b); 
} 
관련 문제