Determining whether a point inside the rectangle

Determining whether a point inside the rectangle

topic

In the two-dimensional coordinate system, all values are double type, a rectangle may be represented by four points,
(X1, Y1) of the left-most point, (x2, y2) to the uppermost point, (X3, y3) is the lowest point, (x4, y4) of the rightmost point.
Given a rectangular four points represented give a fixed point (x, y), is determined (x, y) is in the rectangle.


Algorithm thinking

I think the first reaction is converted is within a range of a plurality of straight lines , it may be extended to Analyzing polygon.
Two may represent a straight line can be determined linear equation
may be used cross product , line orientation point side is determined. See in particular determines whether a two-point method in the vector triangle method .

For a rectangle, a more concise idea.

First, the side of the rectangle parallel to the coordinate axes , easily determined.
By the rotation axis , so that a generally rectangular into a rectangle sides parallel to the coordinate axis, the coordinate points of course changed accordingly.
x = c O s i × x + s i n i × Y Y = s i n i × x + c O s i × Y its in i t x = cos \ theta \ times x + sin \ theta \ times y \\ y = -sin \ theta \ times x + cos \ theta \ times y \\ wherein \ theta axis is rotated counterclockwise arc, with the code t represents

Note:
by location clockwise points were 1,2,4,3

Python3 Code

# 判断特殊矩形:矩形的边平行于坐标轴
def isInParRect(x1, y1, x4, y4, x, y):
    if x <= x1:
        return False
    if x >= x4:
        return False
    if y >= y1:
        return False
    if y <= y4:
        return False
    return True

# 判断一个点是否在矩阵内
# 旋转坐标系,使一般矩形变成边平行于坐标轴的矩形
def isInRect(x1, y1, x2, y2, x3, y3, x4, y4, x, y):
    # 使一般矩形旋转,使之平行于坐标轴
    if x1 != x4:
        # 坐标系以(x3, y3)为中心,逆时针旋转t至(x4, y4)
        dx = x4 - x3
        dy = y4 - y3
        ds = (dx**2 + dy**2)**0.5
        cost = dx / ds
        sint = dy / ds
        # python特性:隐含临时变量存储值
        x, y = cost * x + sint * y, -sint * x + cost * y
        x1, y1 = cost * x1 + sint * y1, -sint * x1 + cost * y1
        x4, y4 = cost * x4 + sint * y4, -sint * x4 + cost * y4
    return isInParRect(x1, y1, x4, y4, x, y)

Have any questions or suggestions, please leave a message in the comments section and correct me!

We appreciate the time and effort you spend!

Published 57 original articles · won praise 44 · views 20000 +

Guess you like

Origin blog.csdn.net/the_harder_to_love/article/details/104180392