问题描述
我创建了一个draw方法来使用Java中的fillpolygon和strokepolygon方法绘制正六边形,目前我一直试图找出如何获取绘制正多边形所需的六个x和y坐标。谁能帮助我? 这是填充多边形的结构:
Public void fillpolygon(double[] xPoints,double[] yPoints,int nPoints)
使用当前设置的填充颜料填充具有给定点的多边形。任何数组的空值都将被忽略,并且不会绘制任何内容。 此方法将受到“渲染属性表”中指定的任何全局通用,填充或填充规则属性的影响。
参数: xPoints-包含多边形点的x坐标的数组,或者为null。 yPoints-包含多边形点的y坐标或为null的数组。 nPoints-构成多边形的点数。
解决方法
我给你写了一堂课来做你需要做的事情:
public class Coordinate {
double x;
double y;
public Coordinate(double x,double y) {
this.x = x;
this.y = y;
}
private static Coordinate fromPolar(double magnitude,double angle) {
double flippedAngle = Math.PI/2 - angle;
return new Coordinate(magnitude * Math.cos(flippedAngle),magnitude * Math.sin(flippedAngle));
}
public static Coordinate[] regularPolygonCoordinates(int sides,double radius) {
Coordinate[] r = new Coordinate[sides];
for (int i = 0 ; i < sides ; i++)
r[i] = fromPolar(radius,2.0 * Math.PI * i / sides);
return r;
}
public static void main(String[] args) {
Coordinate[] hexagon = regularPolygonCoordinates(6,1);
for (Coordinate coord : hexagon) {
System.out.printf("%f,%f\n",coord.x,coord.y);
}
}
}
半径为1.0的六角形的结果:
0.000000,1.000000
0.866025,0.500000
0.866025,-0.500000
0.000000,-1.000000
-0.866025,-0.500000
-0.866025,0.500000
您可以将此代码放入代码中,并在每次需要坐标时调用它,也可以将上述单位六边形的坐标硬编码到代码中,然后按所需的半径缩放所有坐标你的六角形要拥有。
如果要执行后者,则实际上甚至不需要此代码。我在网上找到了这个很酷的Polygon Vertex Calculator,可以为您提供任何“角”的坐标。
如果您确实想直接使用此代码,则可以得到两个分开的顶点数组,如下所示:
double[] xPoints = new double[6];
double[] yPoints = new double[6];
for (int i = 0 ; i < 6 ; i++) {
xPoints[i] = hexagon[i].x;
yPoints[i] = hexagon[i].y;
}