Search code examples
graphicsgeometrycoordinatesdrawing

How to scale a list of 2D coordinates to a desired size


I have a list of 2D coordinates that draw a shape, e.g. [{12, 14}, {22, 44}, {59, 33}, ...]

I'd like to be able to take this shape, and center it in a canvas of arbitrary size (let's say 400x400) and have it take as much space as possible.

I've figured out how to normalize the list so it's in the 0-1 range, but ended up being stuck there when trying to then scale it up to the desired size.

Any help would be appreciated!


Solution

  • Find minimal and maximal values for X and Y coordinates xmin, xmax, ymin, ymax

    Calculate point cloud width and height, and middle coordinates

    cw = xmax - xmin
    ch = ymax - ymin
    mx = (xmax + xmin) / 2
    my = (ymax + ymin) / 2
    

    Now find coefficient

    if cw * canvas.height >= ch * canvas.width
       coeff = canvas.width / cw   
    else
       coeff = canvas.height / ch  
    

    Now get canvas center

    centerx = canvas.width / 2 
    centery = canvas.height / 2 
    

    and apply the next transformation to every point (x,y):

    screenx = centerx + coeff * (x - mx)
    screeny = centery + coeff * (y - my)