我有一个带有按钮的类演示,当用户单击名为“多边形”的按钮时,将从点击的点开始绘制多边形,该代码在绘图中工作正常,但不幸的是它在错误的位置绘制了多边形。
PolygonShape 类
class PolygonShape {
int x, y;
private Polygon p;
public PolygonShape(int x, int y) {
// the x, y sent to this constructor
//are the cordinates of the point where the user clicked
this.x = x;
this.y = y;
}
public void draw(Graphics g) {
p = new Polygon();
for (int i = 0; i < 5; i++)
p.addPoint((int) (x + y * Math.cos(i * 2 * Math.PI / 5)),
(int) (x + y * Math.sin(i * 2 * Math.PI / 5)));
g.drawPolygon(p);
}
}
最佳答案
假设x
和y
是多边形的中心,你使用它们是错误的(你需要将x
添加到x坐标和 y 坐标),并且您缺少另一个重要变量:半径的 r 。您应该在公式中乘以 r
,而不是乘以 y
。
换句话说:
class PolygonShape {
int x, y, r;
private Polygon p;
public PolygonShape(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
// Provide a default radius of 100 pixels if no radius is given.
public PolygonShape(int x, int y) {
this(x, y, 100);
}
public void draw(Graphics g) {
p = new Polygon();
for (int i = 0; i < 5; i++) {
double angle = i * 2 * Math.PI / 5;
p.addPoint((int) (x + r * Math.cos(angle)),
(int) (y + r * Math.sin(angle)));
}
g.drawPolygon(p);
}
}
关于java - 如何计算 5 点多边形中的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26734515/