Java Area与Line的交集

时间:2018-03-29 10:00:19

标签: java line polygon intersection

我试图确定多边形和线是否相交,并且我根据@Vikdor对线程here的回答得到了错误的答案。

我尝试使用Shape.intersectLine(Line2D)和Area.intersects(Area)两者似乎都不起作用,尽管它们在检查Rectangle to Rectangle时确实可以正常工作。最后,我需要能够使用Area.intersects(Area),因为我需要检查在道路上相交的简单多边形。这是我的代码:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;

public class test4 
{
    public static void main(String[] args) 
    {
        Rectangle rect = new Rectangle(20,20,10,10);

        Rectangle rectThatShouldIntersect = new Rectangle(12,12,10,10);
        Rectangle rectThatShouldNotIntersect = new Rectangle(35,35,5,5);

        Line2D.Double lineThatShouldIntersect = new    Line2D.Double(25,0,25,50);
        Line2D.Double lineThatShouldNotIntersect = new Line2D.Double(10,0,10,50);

        System.err.println("Should be true: " + doesIntersectAsArea(new Area(rect), new Area(lineThatShouldIntersect)));
        System.err.println("Should be false: " + doesIntersectAsArea(new Area(rect), new Area(lineThatShouldNotIntersect)));

        System.err.println("Should be true: " + doesIntersectAsArea(new Area(rect), new Area(rectThatShouldIntersect)));
        System.err.println("Should be false: " + doesIntersectAsArea(new Area(rect), new Area(rectThatShouldNotIntersect)));

        System.err.println("Should be true: " + doesIntersect(rect, lineThatShouldIntersect));
        System.err.println("Should be false: " + doesIntersect(rect, lineThatShouldNotIntersect));

        System.err.println("Should be true: " + doesIntersect(rect, rectThatShouldIntersect));
        System.err.println("Should be false: " + doesIntersect(rect, rectThatShouldNotIntersect));

        BufferedImage img = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();  

        g2d.setColor(Color.BLUE);
        g2d.draw(rect);
        g2d.setColor(Color.GREEN);
        g2d.draw(lineThatShouldIntersect);
        g2d.draw(rectThatShouldIntersect);
        g2d.setColor(Color.RED);
        g2d.draw(lineThatShouldNotIntersect);           
        g2d.draw(rectThatShouldNotIntersect);   

        //code to save image
    }

    static public boolean doesIntersectAsArea(Area a, Area b)
    {
        a.intersect(b);
        return !a.isEmpty();
    }   

    static public boolean doesIntersect(Rectangle a, Line2D b)
    {
        a.intersectsLine(b);
        return !a.isEmpty();
    }   

    static public boolean doesIntersect(Rectangle a, Rectangle b)
    {
        a.intersects(b);
        return !a.isEmpty();
    }   
}
  

应该是真的:假
  应该是假的:假的   应该是真的:真实的   应该是假的:假的   应该是真的:真实的   应该是假的:真的   应该是真的:真实的   应该是假的:真实

enter image description here

我错过了一些明显的东西吗?

0 个答案:

没有答案