How do I scale one rectangle to the maximum size possible within another rectangle?

I have a source rectangle and a destination rectangle. I need to find the maximum scale to which the source can be scaled while fitting within the destination rectangle and maintaining its original aspect ratio.

Google found one way to do it but I'm not sure if it works in all cases. Here is my home-brewed solution:

  • Calculate Height/Width for each rectangle. This gives the slopes of the diagonals msrc and mdest.
  • If msrc < mdst, scale source width to fit the destination width (and scale height by the same ratio)
  • Otherwise, scale source height to fit the destination height (and scale width by the same ratio)

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


scale = min(dst.width/src.width, dst.height/src.height)

This is your approach but written more cleanly.


Another option might be to scale to maximum width and then check if the scaled height is greater then the maximum allowed height and if so scale by 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 both shorter, faster and easier to understand.


  1. Work out the smaller of destWidth / srcWidth and destHeight / srcHeight
  2. Scale by that

edit it's of course the same as your method, with the pieces of the formula moved around. My opinion is that this is clearer semantically, but it's only that - an opinion.


If all dimensions are non-zero, I would use the following code (that essentially matches your code).

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

This can also be modified to allow any dimension to be zero if required.