Coordinate Conversion

File: coordinate_conversion.py

#! /usr/bin/python3
# ===================================================================
# coordinate conversion
# ===================================================================

# -------------------------------------------------------------------
# convert window coordinates to center (Cartesian) coordinates
# coordinates are returned as integers
# -------------------------------------------------------------------

def win_to_center_coords(wx,wy,win_width,win_height):

    wcx = win_width  / 2.0     # window center X coordinates
    wcy = win_height / 2.0     # window center Y coordinates

    cx =  round(wx - wcx)
    cy =  round(wcy - wy)

    return (cx,cy)

# -------------------------------------------------------------------
# convert center (Cartesian) coordinates to window coordinates
# coordinates are returned as integers
# -------------------------------------------------------------------

def center_to_win_coords(cx,cy,win_width,win_height):

    wcx = win_width  / 2.0     # window center X coordinates
    wcy = win_height / 2.0     # window center Y coordinates

    wx = round(wcx + cx)
    wy = round(wcy - cy)

    return (wx,wy)


# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

if __name__ == '__main__':

    win_width  = 800
    win_height = 800

    cds1 = [ (50,50), (50,-50), (-50,50), (-50,-50) ]

    for c in cds1:

        xy = center_to_win_coords(c[0],c[1],win_width,win_height)

        print(f'{c}  {xy}')

    print('------------------------------')

    cds2 = [ (450,350), (450,450), (350,350), (350,450) ]

    for c in cds2:

        xy = win_to_center_coords(c[0],c[1],win_width,win_height)

        print(f'{c}  {xy}')