我正在画一个矩形,在上面画一个字符串。这个字符串应该居中(有效),但也应该调整大小,以便“所有”字符串适合这个矩形。
居中有效,但我将把它包括在内,所以这个问题可能会帮助其他想要在矩形上居中和调整字符串大小的人。
问题是 While 循环是无限的。Rectangle2D 始终具有相同的大小......
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
... other paintings ...
Font font = new Font("Courier new", Font.BOLD, MAX_FONTSIZE);
// resize string
Rectangle2D fontRec = font.getStringBounds(information, g2.getFontMetrics().getFontRenderContext());
while(fontRec.getWidth() >= width * 0.95f || fontRec.getHeight() >= height * 0.95f){
Font smallerFont = font.deriveFont((float) (font.getSize() - 2));
g2.setFont(smallerFont);
fontRec = smallerFont.getStringBounds(information,
g2.getFontMetrics().getFontRenderContext());
}
// center string
FontMetrics fm = g2.getFontMetrics();
float stringWidth = fm.stringWidth(information);
int fontX = (int) (x + width / 2 - stringWidth / 2);
int fontY = (int) (y + height / 2);
g2.drawString(information, fontX, fontY);
}
修正是:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
... other paintings ...
// resize string
Rectangle2D fontRec = font.getStringBounds(information, g2.getFontMetrics().getFontRenderContext());
while(fontRec.getWidth() >= width * 0.95f || fontRec.getHeight() >= height * 0.95f){
Font smallerFont = font.deriveFont((float) (font.getSize() - 2));
font = smallerFont;
g2.setFont(smallerFont);
fontRec = smallerFont.getStringBounds(information, g2.getFontMetrics().getFontRenderContext());
}
// center string
FontMetrics fm = g2.getFontMetrics();
float stringWidth = fm.stringWidth(information);
int fontX = (int) (x + width / 2 - stringWidth / 2);
int fontY = (int) (y + height / 2);
g2.drawString(information, fontX, fontY);
}
此代码正确居中并调整字符串大小。