问题描述
我的任务是编写允许用户绘制星星的程序,这些星星的大小和武器数量可能不同。当我处理基本的星星时,我使用的是GeneralPath和积分表:
I have task to write program allowing users to draw stars, which can differ in size and amount of arms. When I was dealing with basic stars I was doing it with GeneralPath and tables of points :
int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
Graphics2D g2d = ( Graphics2D ) g;
GeneralPath star = new GeneralPath();
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
for ( int k = 1; k < xPoints.length; k++ )
star.lineTo( xPoints[ k ], yPoints[ k ] );
star.closePath();
g2d.fill( star );
我应该选择哪种方法来绘制具有可变内径和外径的恒星,以及不同的量武器?这是我应该获得的:
What method should I choose for drawing stars with variable inner and outer radius, as well as different amount of arms ? This is what I should obtain :
推荐答案
拥有武器意味着你结束最多有2n个顶点,偶数个位于外圆上,奇数个位于内圆上。从中心看,顶点处于均匀间隔的角度(角度为2 * PI / 2 * n = Pi / n)。在单位圆(r = 1)上,点i = 0..n的x,y坐标是cos(x),sin(x)。将这些坐标乘以相应的半径(rOuter或rInner,取决于i是奇数还是偶数),并将该向量添加到星的中心,以获得星形路径中每个顶点的坐标。
Having n arms means you end up with 2n vertices, the even ones are on the outer circle, and the odd ones on the inner circle. Viewed from the center, the vertices are at evenly spaced angles (the angle is 2*PI/2*n = Pi/n). On an unit circle (r=1), the x,y coordinates of the points i=0..n is cos(x),sin(x). Multiply those coordinates with the respective radius (rOuter or rInner, depending of whether i is odd or even), and add that vector to the center of the star to get the coordinates for each vertex in the star path.
这是创建具有给定臂数,中心坐标和外半径的内星形状的函数:
Here's the function to create a star shape with given number of arms, center coordinate and outer, inner radius:
public static Shape createStar(int arms, Point center, double rOuter, double rInner)
{
double angle = Math.PI / arms;
GeneralPath path = new GeneralPath();
for (int i = 0; i < 2 * arms; i++)
{
double r = (i & 1) == 0 ? rOuter : rInner;
Point2D.Double p = new Point2D.Double(center.x + Math.cos(i * angle) * r, center.y + Math.sin(i * angle) * r);
if (i == 0) path.moveTo(p.getX(), p.getY());
else path.lineTo(p.getX(), p.getY());
}
path.closePath();
return path;
}
这篇关于使用可变参数绘制星形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!