由Line2D填充的颜色形状

时间:2017-05-02 12:58:18

标签: java graphics2d

在java中,我通过使用2D线连接点来创建闭合形状。我怎样画它/填充颜色?

2 个答案:

答案 0 :(得分:1)

首先,通过将您的行添加到Path2D

来创建单个Shape
private Path2D createSingleShape(Line2D[] lines) {
    Path2D path = new Path2D.Float();

    for (Line2D line : lines) {
        path.append(line, path.getCurrentPoint() != null);
    }

    path.closePath();

    return path;
}

然后,将其传递给Graphics2D.fill(Shape)

@Override
protected void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);

    Graphics2D g = (Graphics2D) graphics;

    Shape shape = createSingleShape(lines);
    g.fill(shape);
}

答案 1 :(得分:-1)

我不知道你的代码是什么,但我假设你有一个类似这样的类:

您正在搜索fillPolygon(int[] xpoints, int[] ypoints, int nPoints)方法

public class App extends JFrame{
    public App() {
        super("Paintings");
        requestFocus();
        DrawingPane dpane=new DrawingPane();
        setContentPane(dpane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);
        setResizable(true);
        setVisible(true);
        long start = System.currentTimeMillis();
        while (true){
            long now = System.currentTimeMillis();
            if (now-start > 10) { //FPS
                start=now;
                dpane.revalidate();
                dpane.repaint();
            }
        }
    }
    public static void main(String[] args) {
        new App();
    }
    class DrawingPane extends JPanel{
        @Override
        public void paintComponent(Graphics g2){
            Graphics2D g=(Graphics2D)g2;
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setColor(Color.BLACK);
            //-THE DRAWING-
            //You wont need any lines
            Point[] points=new Point[] {new Point(0,0),new Point(1,0),new Point(1,1)};
            int[] points_x=new int[points.length];
            int[] points_y=new int[points.length];
            for (int p=0; p < points.length; p++) {
                 points_x[p]=points[p].x;
                 points_y[p]=points[p].y;
            }
            g.drawPolygon(points_x,points_y,points.length); //Draw the outlines
            g.fillPolygon(points_x,points_y,points.length); //Filled Polygon
        }
    }
}