绘制随机粗细线

时间:2012-09-08 04:26:35

标签: java

我正在尝试使用setStrokeBasicStroke绘制随机粗细线。

这是绘画代码

 public void paintComponent(Graphics g1) {
        Random rand = new Random();
        Graphics g2 = (Graphics2D) g1;

        //set background color
        g2.setColor(Color.white);
        g2.fillRect(0, 0, getWidth(), getHeight());
        Dimension d = getPreferredSize();

        //set  line's color

        float r = rand.nextFloat();
        float g = rand.nextFloat();
        float b = rand.nextFloat();

        Color randomColor = new Color(r,g,b);

        g2.setColor(randomColor);

        //set line's stroke

        float width = rand.nextFloat();

        BasicStroke randomStroke = new BasicStroke(width);


        ((Graphics2D) g2).setStroke(randomStroke);


        for (Line2D.Double line : lines) {
            g2.drawLine(
                (int)line.getX1(),
                (int)line.getY1(),
                (int)line.getX2(),
                (int)line.getY2()
                );
        }
    }

当我将笔画宽度设置为某个数字时,它可以正确绘制。我查了BasicStroke类,它有以下参数:

  float width;
  int join;
  int cap;
  float miterlimit;
  float[] dash;
  float dash_phase;

除了宽度,我不确定其他功能是什么。 如何使用BasicStroke生成随机粗细线?

1 个答案:

答案 0 :(得分:2)

我认为最大的问题是nextFloat()返回0到1之间的值 - 我猜你想要大于1的数字,以便能够看到线条厚度的任何明显差异。

  

除了宽度,我不确定其他功能是什么。

请参阅the Javadocs

相关问题