setstroke rectangulo poligono java2d estrella ejemplos dibujar clase java text draw centering graphics2d

rectangulo - ¿Cómo puedo centrar Graphics.drawString() en Java?



rectangulo en java2d (2)

Actualmente estoy trabajando en el sistema de menús de mi juego Java , y me pregunto cómo puedo centrar el texto de Graphics.drawString() , de modo que si quiero dibujar un texto cuyo punto central esté en X: 50 e Y: 50 , y el texto tiene 30 píxeles de ancho y 10 píxeles de alto, el texto comenzará en X: 35 e Y: 45 .

¿Puedo determinar el ancho del texto antes de dibujarlo?
Entonces sería matemáticas fáciles.

EDITAR: También me pregunto si puedo obtener la altura del texto, por lo que también puedo centrarlo verticalmente.

Cualquier ayuda es apreciada!


Cuando tengo que dibujar texto, normalmente necesito centrar el texto en un rectángulo delimitador.

/** * 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); }


Utilicé la respuesta a esta pregunta .

El código que usé se ve algo como esto:

/** * 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); }