Last active
February 22, 2017 01:26
-
-
Save MaartenBaert/0fc3a2b875beeae5969f01ed8fd102f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pylab import * | |
def segment_intersects_rectangle(x1, y1, x2, y2, cx, cy, w, h): | |
return (fabs(x1 + x2 - 2.0 * cx) < fabs(x1 - x2) + w and | |
fabs(y1 + y2 - 2.0 * cy) < fabs(y1 - y2) + h and | |
2.0 * fabs((x1 - cx) * (y1 - y2) - (y1 - cy) * (x1 - x2)) < w * fabs(y1 - y2) + h * fabs(x1 - x2)) | |
def test_intersect(plot_line, plot_rect): | |
for line in plot_line: | |
(x1, x2) = line.get_xdata() | |
(y1, y2) = line.get_ydata() | |
rx = plot_rect[0].get_xdata() | |
ry = plot_rect[0].get_ydata() | |
cx = (rx[0] + rx[2]) / 2.0 | |
cy = (ry[0] + ry[2]) / 2.0 | |
w = abs(rx[0] - rx[2]) | |
h = abs(ry[0] - ry[2]) | |
res = segment_intersects_rectangle(x1, y1, x2, y2, cx, cy, w, h) | |
line.set_color("r" if res else "g") | |
def mouse_move(event): | |
if event.xdata is not None and event.ydata is not None: | |
rx = plot_rect[0].get_xdata() | |
ry = plot_rect[0].get_ydata() | |
w2 = abs(rx[0] - rx[2]) / 2.0 | |
h2 = abs(ry[0] - ry[2]) / 2.0 | |
plot_rect[0].set_xdata(event.xdata + array([-w2, w2, w2, -w2, -w2])) | |
plot_rect[0].set_ydata(event.ydata + array([h2, h2, -h2, -h2, h2])) | |
test_intersect(plot_line, plot_rect) | |
fig.canvas.draw() | |
close("all") | |
fig = figure("Line-Rect test", figsize=(8, 8)) | |
ax = subplot(1, 1, 1) | |
t = linspace(0, 2 * pi, 81) | |
px = sin(3 * t) | |
py = cos(5 * t) | |
lx = vstack((px[:-1], px[1:])) | |
ly = vstack((py[:-1], py[1:])) | |
rx = array([3.2, 4.1, 4.1, 3.2, 3.2]) | |
ry = array([4.3, 4.3, 2.7, 2.7, 4.3]) | |
plot_line = plot(lx, ly, ".-") | |
plot_rect = plot(rx, ry, ".-", color="b") | |
test_intersect(plot_line, plot_rect) | |
fig.canvas.mpl_connect("motion_notify_event", mouse_move) | |
xlim(-2, 2) | |
ylim(-2, 2) | |
tight_layout() | |
show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment