Domanda

Sto cercando di centrare una stringa disegnato con "un" sistema", Font.BOLD, 90" font in Java. Ho provato. (Larghezza / 2 - (Font.Size / 2 * num_of_chars)), ma che non ha funzionato

g2d.setFont(new Font("system", Font.BOLD, 90));
g2d.drawString("Pause", (int) ((800/2) - ((Font.getSize()/2) * 5)),270);
È stato utile?

Soluzione

getFontMetrics() . getStringBounds(String, Graphics) per ottenere i limiti della stringa con il font corrente.

Quindi sarebbe simile a questa:

g2d.setFont(new Font("system", Font.BOLD, 90));
String msg = "Pause";
Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(msg, g2d);
g2d.drawString(msg, (int) ((getWidth() + bounds.getWidth()) / 2), 270);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top