我必须在椭圆形或圆形上写文字
我有这段代码(我在Stackoverflow上找到了它),但是我不明白某些要点。
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panneau extends JPanel {
@Override
public void paintComponent(Graphics g){
// Declaration
String text = "test";
int x = 100, y = 50;
int ovalWidth = 50, ovalHeight = 50;
// Draw circle
g.setColor(Color.blue);
g.fillOval(x-ovalWidth/2, y-ovalHeight/2,ovalWidth, ovalHeight);
// I don't understand why x-ovalwidth/2 and y-ovalheight/2
// Put text into circle
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
// What is the job of getstringbounds
g.setColor(Color.white);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
}
}
谢谢
最佳答案
使用Graphics Documentation中的信息
fillOval( x, y, width, height)
x - the x coordinate of the upper left corner of the oval to be filled.
y - the y coordinate of the upper left corner of the oval to be filled.
width - the width of the oval to be filled.
height - the height of the oval to be filled.
因此,您要告诉图形绘制一个圆,其中左上角为x-(宽度的一半),y-(高度的一半)。原因是,它使圆偏移,因此圆的中心位于(x,y)而不是左上角。
getStringBounds
Returns:
a Rectangle2D that is the bounding box of the specified String in the
specified Graphics context.
(返回一个足以容纳字符串的矩形)
不用说,当您使用各种Java类时,该文档对查看很有帮助。