简体   繁体   中英

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.

I'm not sure I get the question right, but if I do, it should be pretty easy:

1.Check which of your new sides ( x or y ) is smaller in size;

2.Get the ratio of scale by dividing x/w (if x<y ) or y/h (if y<x );

3.Once you know the ratio, proportionally scale your path with that value.

The way you do your last step, it depends on how you keep/draw your array. If it's just a simple points buffer, the you can use matrix scaling . Also, although it beats the scope of the question, if you need to do it really fast (the path has lots of points) check out Apple's Accelerate framework for matrix/vector multiplying.

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.

Get the difference between each of the two x and y coordinates. Determine which is the greater percentage difference, then the multiply the coordinates used in drawing the curve by that percentage. The result will be the curve in a size that will just fit into the smaller box.

You may have to add an offset to the coordinates of the curve to position it within the box correctly.

Depending on your needs, it may be better to look for a drawing API though, rather than doing this manually, as you may get some free (or cheap) functionality like having the user be able to pinch scale, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM