Blog Archives

UIImageView aspectFit and center

Recently, I come across with a limitation where IOS SDK does not let us specified image view property to multiple flag. (e.g flagA | flagB in Android does).
There are several option out there using custom class extending the UIImageView.

For this post I will show you how to set UIImageView aspectFit and Center together (ugly workaround), this solution is not the best and has some side effect to the performance, but it is an option for people who still want it.

First, I calculate the ratio that needed to resize and set that as my new frame width/height. Then, using the new information I got, set the starting point of my frame.

If you use an UIImageView from interface.builder and set it to aspectFit, below can help you load your image programmatically and still display in center horizontal.

UIImageView *tmpView = (UIImageView *)[tmp_controller.cellPhoto viewWithTag:image_tag];
[tmpView setContentMode:UIViewContentModeScaleAspectFit];
CGSize kMaxImageViewSize = {.width = 200, .height = 200}; //set your max desire width and height here
CGSize imageSize = image.size;
CGFloat aspectRatio = imageSize.width / imageSize.height;
CGRect frame = tmpView.frame;

if (kMaxImageViewSize.width / aspectRatio <= kMaxImageViewSize.height) {
frame.size.width = kMaxImageViewSize.width;
frame.size.height = frame.size.width / aspectRatio;
} else {
frame.size.height = kMaxImageViewSize.height;
frame.size.width = frame.size.height * aspectRatio;

CGFloat startPointX = (self.view.frame.size.width/2) - (frame.size.width/2);
tmpView.frame = CGRectMake(startPointX,tmpView.frame.origin.y,frame.size.width, frame.size.height);
tmpView.image = [info objectForKey:UIImagePickerControllerOriginalImage]; //Getting image from photo album