如何使用循环中的线填充三角形

时间:2013-12-14 07:16:52

标签: java loops geometry fill

我无法弄清楚这背后的逻辑。我在Java中绘制了一个三角形,但现在我试图用For循环中的线填充该三角形。

有人可以告诉我我做错了什么吗?

import java.awt.Graphics;

import javax.swing.JApplet;

public class Triangle extends JApplet {

int x1 = 300;
int x2 = 206;
int y2 = 206;
int y1 = 71;
int y3 = 206;
int x3 = 400;

public void paint(Graphics page) {
    page.drawLine (x1,y1,x2,y2);
    page.drawLine(x2, y2, x3, y3);
    page.drawLine(x3, y3, x1, y1);


    for (x1 = 300; x1<= 506 ; x1++){
        page.drawLine(x3, y3, x1, y1);


    }


}

}

1 个答案:

答案 0 :(得分:0)

您应该使用page.fillPoly()

int[] xPoints = {x1, x2, x3};
int[] yPoints = {y1, y2, y3};
page.fillPoly(xPoints, yPoints, 3);

请参阅Graphics#fillPoly()

编辑:尝试这样的事情,对于颠倒的半金字塔

int x1 = 0;
int y1 = 0;
int x2 = 100;
int y2 = 0;

for (int i = 0; i < x2; i++){
    g.drawLine(x1, y1, x2, y2);
    x1 += 1;
    y1 += 1;
    y2 += 1;
}

这还没有经过测试,但我假设应该打印这样的东西

--------------
 -------------
  ------------  // with no spaces of course.
   -----------
    ----------
     ---------
      --------
 .. and so on

这只是一个猜测。


编辑:经过测试和批准:)

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JPanel {

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int x1 = 0;
        int y1 = 0;
        int x2 = 100;
        int y2 = 0;

        for (int i = 0; i < x2; i++) {
            g.drawLine(x1, y1, x2, y2);
            x1 += 1;
            y1 += 1;
            y2 += 1;
        }
    }

    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new Test());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

结果

enter image description here