【问题标题】:Java: Drawing "Random" StarsJava:绘制“随机”星星
【发布时间】: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


【解决方案1】:

慢慢积累。先集中定位两颗星,就两颗。选择星星中心的坐标并放置它们。调整以使其正确(您的第一次尝试可能会出错)。测试,修复,再测试,再修复。重复。

然后玩弄尖刺和其他变化,使星星不一样。什么时候,也只有什么时候,那是经过测试和工作的,然后才能继续前进到三、四等星。星星越多,您就必须更加小心以避免重叠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多