1. 程式人生 > 其它 >python 求直線延長線和矩形的交點

python 求直線延長線和矩形的交點


# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         test
# Author:       yunhgu
# Date:         2022/4/13 14:00
# Description: 
# -------------------------------------------------------------------------------
from PIL import ImageDraw, Image


def getLinearEquation(point1, point2):
    p1x, p1y = point1
    p2x, p2y = point2
    sign = 1
    a = p2y - p1y
    if a < 0:
        sign = -1
        a = sign * a
    b = sign * (p1x - p2x)
    c = sign * (p1y * p2x - p1x * p2y)
    return [a, b, -c]


def get_intersection(rectangle_point, point1, point2):
    intersection_list = []
    a, b, c = getLinearEquation(point1, point2)
    x_list = [rectangle_point[0], rectangle_point[2]]
    y_list = [rectangle_point[1], rectangle_point[3]]
    if b == 0:
        y = point1[-1]
        if y_list[0] <= y <= y_list[1]:
            intersection_list.extend([(point1[0], y_list[0]), (point2[0], y_list[1])])
    elif a == 0:
        x = point1[0]
        if x_list[0] <= x <= x_list[1]:
            intersection_list.extend([(x_list[0], point1[1]), (x_list[1], point1[1])])
    else:
        for x in x_list:
            y = (c - a * x) / b
            if rectangle_point[1] <= y <= rectangle_point[3]:
                intersection_list.append((x, y))
        for y in y_list:
            x = (c - b * y) / a
            if rectangle_point[0] <= x <= rectangle_point[2]:
                intersection_list.append((x, y))
    return intersection_list


img = Image.new("RGB", (500, 500))
draw = ImageDraw.Draw(img)
rectangle = (50, 50, 250, 250)  # (x0,y0,x1,y1)
draw.rectangle(rectangle, outline="blue")

pt1 = (200, 30)
pt2 = (150, 200)

intersections = get_intersection(rectangle, pt1, pt2)
print(intersections)
draw.line(intersections, fill="green", width=6)
draw.line((pt1, pt2), fill="red", width=2)
img.show()