iOS: compute the aspect-fit rectangle of an image within a given rectangular container
I seldom share code snippets. However, it must be acknowledged that simple geometric operations are not always well understood by many programmers. As a consequence, they often come up with long and complex source code that is not even solid, leaving room for bugs.
The objective is to compute the bounding rectangle of an image placed inside a given rectangular container, so that the image is scaled to fit within it while preserving its original aspect ratio.
In addition, the code centers the image within the bounding view.
The first step is to compute the two possible scale factors. Since we are looking for the maximum constraint, we pick the smaller scale factor to decide which dimension to preserve. Then we recompute the second dimension by combining the two scale factors.
The resulting code is short and straightforward:
<code>
<pre>
- (CGRect) getAspectFitRectangle:(UIImageView *)iv
image:(UIImage *)im {
// view to embed the image
float vw = iv.frame.size.width;
float vh = iv.frame.size.height;
}
</code>
</pre>