#! /usr/bin/python3 # =================================================================== # coordinate transformation # 10/26/2020 # =================================================================== # Computer graphics window coordinate systems usually have their # origin (0,0) in the upper left corner of the window. X coordinates # increase to the right and Y coordinates increase downward. # # Centered coordinate systems have their origin (0,0) in the # center of the window. # =================================================================== # ------------------------------------------------------------------- # convert window coordinates to center 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 if wx > wcx: cx = int(round(wx - wcx)) else: cx = int(round(wx - wcx)) if wy > wcy: cy = int(round(wcy - wy)) else: cy = int(round(wcy - wy)) return (cx,cy) # ------------------------------------------------------------------- # convert center 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 if cx < 0.0: wx = int(round(wcx + cx)) else: wx = int(round(wcx + cx)) if cy < 0.0: wy = int(round(wcy - cy)) else: wy = int(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}')