【发布时间】:2017-04-04 03:45:03
【问题描述】:
我正在尝试使用此代码,我终于开始为绘制一颗星而工作,并且对如何让它为绘制 25 颗不同的星(例如不同的侧面和尖峰度)工作感到困惑,但我不确定如何准确地进行. 我假设我会创建一个新的随机变量int randomStars = (int)(Math.random()*25+1); // Variable for 25 Random Stars 来随机生成星星,但我有点困惑从哪里获取它。
非常感谢您的帮助。
我的代码(使用DrawingPanel.java):
import java.awt.*;
public class StarSampler {
public static void main(String[] args)
{
DrawingPanel panel = new DrawingPanel(500, 500);
Graphics2D g = panel.getGraphics();
g.setColor(Color.BLUE);
panel.setBackground(new Color(250, 0, 0));
fillStar(g, 250, 250, 150, 5, .3); // How to rotate it to start at center?
}
public static void fillStar(Graphics2D g, int ctrX, int ctrY, int radius, int nPoints, double spikiness)
{
double xDouble[] = new double[2*nPoints];
double yDouble[] = new double[2*nPoints];
int xPoint[] = new int[2*nPoints];
int yPoint[] = new int[2*nPoints];
nPoints = (int) (nPoints * 2);
int randomStars = (int)(Math.random()*25+1); // Variable for 25 Random Stars
// Would Nestest loop go here? for (randomStars++; randomStars < 25; randomStars++)
for (int i = 0; i < nPoints; i++)
{
double iRadius = (i % 2 == 0) ? radius : (radius * spikiness);
double angle = (270) + (i * 360.0) / (nPoints);
xPoint[i] = (int) (ctrX + iRadius * Math.cos(Math.toRadians(angle)));
yPoint[i] = (int) (ctrY + iRadius * Math.sin(Math.toRadians(angle)));
}
g.fillPolygon(xPoint, yPoint, nPoints); // Creates polygon
}
}
我的输出:
【问题讨论】:
-
你想把它们一个接一个地画还是一个接一个地画?
-
@Paul 目标彼此相邻,但我想如果它们不完全相互重叠,任何地方都可以随机工作。
-
好的。首先:您需要为每颗星创建两个数字(假设它们的大小相同):半径和尖刺。然后使用
fillStar方法来渲染星星。只需遍历要插入星星的位置并将它们用作中心坐标。
标签: java loops random drawing polygon