How to scale one rectangle to the maximum size possible within another rectangle

algorithmscaling

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!

Best Answer

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

This is your approach but written more cleanly.