[英]Text in center of Circle
There is a circle (planet), drawn through fillOval(). 有一个通过fillOval()绘制的圆(行星)。 I need to write the text (number) on the circle, so that it must be always aligned exactly in the center.
我需要在圆上写文字(数字),以便它必须始终在中心精确对齐。 There is a center of the circle and its radius.
有一个圆心及其半径。 I understand that I need to calculate the width and length of the text (tried by getStringBounds), but does not work correctly.
我了解我需要计算文本的宽度和长度(由getStringBounds尝试),但是无法正常工作。
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Planet planet : planets) {
g2d.setColor(planet.getColor());
g2d.fillOval((int) planet.getX() - planet.getRadius(), (int) planet.getY() - planet.getRadius(),
planet.getRadius() * 2, planet.getRadius() * 2);
g.setFont(new Font("Serif", Font.PLAIN, 20));
g.setColor(Color.black);
String s = String.valueOf(250);
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(s, g).getWidth();
g.setColor(Color.white);
g.drawString(s, (int) ((int) planet.getX() - textWidth/2), ((int) planet.getY() + fm.getMaxAscent() / 2));}}
You're using planet.getX()-planet.getRadius()
and planet.getY() - planet.getRadius()
to calculate your centered point of the circle. 您正在使用
planet.getX()-planet.getRadius()
和planet.getY() - planet.getRadius()
来计算圆心。
Then you have to add the Text you want to paint at the centered position, which is calculated 然后,您必须在要计算的居中位置添加要绘制的文本
planet.getX() - planet.getRadius() - textWidth/2 //or centered point - textWidth/2
which is your x-coordinate and 这是您的x坐标,
planet.getY() - planet.getRadius() + fm.getMaxAscent() / 2 //or centered point + fm.getMaxAscent()/2
which will be the y-coordinate. 这将是y坐标。
But you are using planet.getX() - textWidth/2
但是您正在使用
planet.getX() - textWidth/2
This origin point has to be the center of the circle, not planet.getX()
该原点必须是圆的中心,而不是
planet.getX()
In the past I've had to use both the ascent/descent values to calculate actual font height and it looks like you're only using ascent. 过去,我不得不同时使用ascent / descent值来计算实际的字体高度,并且看起来您只是在使用ascent。 Something to consider: not all strings will have the same max ascent/descent for a given font, so while the string "Dojo" may appear to be properly vertically aligned, the strings "cujo" and "coco" might not.
需要考虑的事情:对于给定的字体,并不是所有的字符串都具有相同的最大上升/下降斜率,因此,虽然字符串“ Dojo”看起来似乎正确地垂直对齐,但是字符串“ cujo”和“ coco”却可能没有。
Another suggestion: instead of calculating the half-width of your text and using that to offset your drawing starting position, why not just center justify the text? 另一个建议:为什么不计算文本的半角宽度并使用它来抵消图形的起始位置,为什么不将文本居中对齐呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.