Fitting a Rectangle Inside a Rectangle

A common problem in computer graphics and user interfaces is scaling one rectangle to fit inside another—preserving the rectangle’s aspect ratio. For example, I’ve encountered this problem in the following situations:

  • Placing an image of arbitrary size on a button of fixed size.
  • Overlay a map on a corner of a game scene.
  • Squeezing an image to fit on a mobile phone screen.

When I first encountered the problem, I just hacked away until I found some scale factors and logic that did the trick. But now that I’ve solved it N times, I need a little more certainty that I am doing the right thing. So, I sat down to prove to myself that my solution works.




Leave a Reply

Your email address will not be published. Required fields are marked *