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.
destWidth / srcWidth
and destHeight / srcHeight
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With