Home > Back-end >  How can you calculate where the middle of the screen is using math in python
How can you calculate where the middle of the screen is using math in python

Time:11-08

I must've skipped school that day because I cannot remember how to calculate the middle of a square.

CodePudding user response:

There are a few different ways to calculate the middle of a square using Python. One way is to find the average of the x and y coordinates of the square's four corners. Another way is to find the point that is equidistant from all four corners of the square.

# method-1
def square_middle(square):
    x1, y1, x2, y2 = square
    return ((x1   x2) / 2, (y1   y2) / 2)

# method-2    
def square_middle(square):
    x1, y1, x2, y2 = square
    cx = (x1   x2) / 2
    cy = (y1   y2) / 2
    return (cx, cy)

CodePudding user response:

frameworks usually report the size of a screen with 2 values or a touple of 2. For example, this is how pyautogui reports it:

print(pyautogui.size())
Size(width=1728, height=1117)

And this is how that framework gets the center for every coordinates tuple: https://github.com/asweigart/pyscreeze/blob/master/pyscreeze/__init__.py#L579 So you can safely use the example above to get the center of any object on screen, even the screen itself.

  • Related