Python Test If Point is in Rectangle

后端 未结 2 1002
日久生厌
日久生厌 2021-01-13 08:55

I am new to python and still learning the ropes but I am hoping someone with more experience can help me out.

I am trying to write a python script that:

相关标签:
2条回答
  • 2021-01-13 09:40

    It is better to write a separate function to do the job. Here's my function. You can just copy it if you want

    def pointInRect(point,rect):
        x1, y1, w, h = rect
        x2, y2 = x1+w, y1+h
        x, y = point
        if (x1 < x and x < x2):
            if (y1 < y and y < y2):
                return True
        return False
    
    0 讨论(0)
  • 2021-01-13 09:56

    This is pretty simple math. Given a rectangle with points (x1,y1) and (x2,y2) and assuming x1 < x2 and y1 < y2 (if not, you can just swap them), a point (x,y) is within that rectangle if x1 < x < x2 and y1 < y < y2. Since Python comparison operators can be chained, this is even valid Python code which should produce the correct result (in other languages you'd have to write something like x1 < x and x < x2, etc).

    If you want, you can use <= instead of <. Using <= means points on the boundary of the rectangle (eg, the point (x1,y1)) count as being inside it, while using < so means such points are outside it.

    0 讨论(0)
提交回复
热议问题