我将如何绘制一个字符串/字符数组,以便将其写成正方形,字符之间的间距相等?数组越大,正方形越大。有没有办法将字符数除以长度并获得矩形中的某些坐标?
我考虑过遍历数组并使用 for 循环获取字符串的整个长度。然后让它成为我方边的长度。但我无法想象如何去做。
Use getFontMetrics() to find out how much space the string will take up, and then draw character by character, adding the required extra space. Here is the code:
import java.awt.*;
// ...
@Override
public void paint(Graphics g) {
String testString = "The quick brown fox jumps.";
Rectangle testRectangle = new Rectangle(10, 50, 200, 20);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.draw(testRectangle);
FontMetrics fm = g2d.getFontMetrics();
int stringWidth = fm.stringWidth(testString);
int extraSpace = (testRectangle.width - stringWidth) / (testString.length() - 1);
int x = testRectangle.x;
int y = testRectangle.y + fm.getAscent();
for (int index = 0; index < testString.length(); index++) {
char c = testString.charAt(index);
g2d.drawString(String.valueOf(c), x, y);
x += fm.charWidth(c) + extraSpace;
}
}
And this is what it looks like:
In order to get more accurate results Graphics2D
also allows you to calculate with float
instead of int
.