Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.