Search code examples
iosmathdrawingnormalization

Scale Coordinates while Maintaining the Aspect ratio in iOS


I have an array of 2D coordinates that I use to draw curve in a box (w,h). Now I want to scale the coordinates into a box (x,y) where x or y or both are smaller than w and h. The Trick part is that I have to maintain the aspect ratio. Any Help would be very much appreciated.


Solution

  • If you need to keep the ratio you need to aspect fit or aspect fill. Either way you need to find one scale factor for both the x and the y transforms.

    First calculate the individual sacling factors for both the X and the Y

    (w1, h1) -> (w2, h2)  (assuming all floats)
    
    float xScaleFactor = w2 / w1;
    float yScaleFactor = h2 / h1;
    

    Now since you are making it smaller take either the smallest scale factor for aspect fit or the biggest scale factor for aspect fill.

    float scaleFactor = MIN(xScaleFactor, yScaleFactor); // Assuming aspect fit
    

    Now simply multiply each point's x and y component by the scale factor.