1
2
3
4
5
6
7
8
9 package edu.uci.ics.jung.visualization.transform.shape;
10
11 import java.awt.Rectangle;
12 import java.awt.geom.Line2D;
13 import java.awt.geom.Point2D;
14 import java.util.HashSet;
15 import java.util.Set;
16
17 public class Intersector {
18
19 protected Rectangle rectangle;
20 Line2D line;
21 Set<Point2D> points = new HashSet<Point2D>();
22
23 public Intersector(Rectangle rectangle) {
24 this.rectangle = rectangle;
25 }
26
27 public Intersector(Rectangle rectangle, Line2D line) {
28 this.rectangle = rectangle;
29 intersectLine(line);
30 }
31
32 public void intersectLine(Line2D line) {
33 this.line = line;
34 points.clear();
35 float rx0 = (float) rectangle.getMinX();
36 float ry0 = (float) rectangle.getMinY();
37 float rx1 = (float) rectangle.getMaxX();
38 float ry1 = (float) rectangle.getMaxY();
39
40 float x1 = (float) line.getX1();
41 float y1 = (float) line.getY1();
42 float x2 = (float) line.getX2();
43 float y2 = (float) line.getY2();
44
45 float dy = y2 - y1;
46 float dx = x2 - x1;
47
48 if(dx != 0) {
49 float m = dy/dx;
50 float b = y1 - m*x1;
51
52
53 float x = (ry0 - b) / m;
54
55 if(rx0 <= x && x <= rx1) {
56 points.add(new Point2D.Float(x, ry0));
57 }
58
59
60 x = (ry1 - b) / m;
61 if(rx0 <= x && x <= rx1) {
62 points.add(new Point2D.Float(x, ry1));
63 }
64
65
66 float y = m * rx0 + b;
67 if(ry0 <= y && y <= ry1) {
68 points.add(new Point2D.Float(rx0, y));
69 }
70
71
72
73 y = m * rx1 + b;
74 if(ry0 <= y && y <= ry1) {
75 points.add(new Point2D.Float(rx1, y));
76 }
77
78 } else {
79
80
81 float x = x1;
82 if(rx0 <= x && x <= rx1) {
83 points.add(new Point2D.Float(x, ry0));
84 }
85
86
87 x = x2;
88 if(rx0 <= x && x <= rx1) {
89 points.add(new Point2D.Float(x, ry1));
90 }
91 }
92 }
93 public Line2D getLine() {
94 return line;
95 }
96 public Set<Point2D> getPoints() {
97 return points;
98 }
99 public Rectangle getRectangle() {
100 return rectangle;
101 }
102
103 public String toString() {
104 return "Rectangle: "+rectangle+", points:"+points;
105 }
106
107 public static void main(String[] args) {
108 Rectangle rectangle = new Rectangle(0,0,10,10);
109 Line2D line = new Line2D.Float(4,4,5,5);
110 System.err.println(""+new Intersector(rectangle, line));
111 System.err.println(""+new Intersector(rectangle, new Line2D.Float(9,11,11,9)));
112 System.err.println(""+new Intersector(rectangle, new Line2D.Float(1,1,3,2)));
113 System.err.println(""+new Intersector(rectangle, new Line2D.Float(4,6,6,4)));
114 }
115
116 }