How to scale one rectangle to the maximum size in another rectangle?

I have a source rectangle and a destination rectangle. I need to find the maximum scale at which the source can be scaled when installed in the destination rectangle and maintaining its original aspect ratio.

Google has found one way , but I'm not sure if it works in all cases. Here is my home solution:

  • Calculate the height / width for each rectangle. This gives the slopes of the msrc and mdest .
  • If msrc < mdst , set the width of the image source according to the width of the destination (and the height of the scale by the same factor)
  • Otherwise, scale the height of the source so that it matches the destination height (and the scale width by the same factor).

We are looking for other possible solutions to this problem. I'm not even sure if my algorithm works in all cases!

+42
algorithm scaling
Sep 03 '09 at 12:11
source share
4 answers
 scale = min( dst.width/src.width, dst.height/src.height) 

This is your approach, but written more cleanly.

+83
03 Sep '09 at 14:50
source share

Another option would be to scale to the maximum width, and then check if the increased height will be greater than the maximum allowable height and if it will scale in height (or vice versa):

 scale = (dst.width / src.width); if (src.height * scale > dst.height) scale = dst.height / src.height; 

I think this solution is shorter, faster and more understandable.

+10
03 Sep '09 at 12:18
source share
  • Design less destWidth / srcWidth and destHeight / srcHeight
  • Scale of this

edit it, of course, like your method, with the fragments of the formula moving. My opinion is that it is clearer semantically, but this is just that - an opinion.

+1
Sep 03 '09 at 12:14
source share

If all measurements are not null, I would use the following code (which essentially matches your code).

 scaleFactor = (outerWidth / outerHeight > innerWidth / innerHeight) ? outerHeight / innerHeight : outerWidth / innerWidth 

This can also be changed so that, if necessary, any measurement is zero.

+1
Sep 03 '09 at 12:41
source share



All Articles