Article

← Retour au blog

🇫🇷 Lire en français

iOS: compute the aspect-fit rectangle of an image within a given rectangular container

2013-05-18 #892 · rév. 1 · EN

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;

// image to be embeded in the view float w = im.size.width; float h = im.size.height; // compute float scaleW = vw/w; float scaleH = vh/h; if (scaleW>scaleH) { // keep height, recompute width float iw = vw/scaleW*scaleH; // compute horizontal translation // to center the image float x = (vw-iw).5f; return CGRectMake(x,0, iw,vh); } else { // keep width, recompute height float ih = vh/scaleH*scaleW; // compute vertical translation // to center the image float y = (vh-ih).5f; return CGRectMake(0,y, vw,ih); }
}
</code>
</pre>