iOS: compute the aspect fit rectangle of an image within a given rectangular container
I seldom give code snippet. But it must be recognized that simple geometrical operations are not really understood by most of programmers. As a consequence, they often come up with long and complex source code which is even not solid, bugs being around.
The objective is to compute the bounding rectangle of an image which is placed in a given rectangular container, so that the image is stretched to fit into it, keeping the original image aspect ratio.
In addition, the code center the image within the bounding view.
The first step is to compute the two possible scale factor. As we're looking for the maximum constraint, we pick the smaller scale factor to decide what direction to keep. Then we recompute the second direction by combining the two scale factors.
The resulting code is short, as follows:
- (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); } }