Skip to content

Instantly share code, notes, and snippets.

@justindhill
Created September 10, 2014 20:51
Show Gist options
  • Select an option

  • Save justindhill/181574ed79e084a11d43 to your computer and use it in GitHub Desktop.

Select an option

Save justindhill/181574ed79e084a11d43 to your computer and use it in GitHub Desktop.
- (CGSize)sizeThatFits:(CGSize)size {
CGSize imageSize = self.imageView.image.size;
if (CGSizeEqualToSize(imageSize, CGSizeZero)) {
return CGSizeZero;
}
if (imageSize.width <= size.width && imageSize.height <= size.height)
return imageSize;
CGFloat deltaWidth = size.width - imageSize.width;
CGFloat deltaHeight = size.height - imageSize.height;
CGSize resultSize;
if (deltaWidth < deltaHeight) {
// constrain the width
CGFloat imageWidthToConstrainedWidthRatio = imageSize.width / size.width;
resultSize = CGSizeMake(size.width, imageSize.height * (1 / imageWidthToConstrainedWidthRatio));
} else {
// constrain the height
CGFloat imageHeightToConstrainedHeightRatio = imageSize.height / size.height;
resultSize = CGSizeMake(imageSize.width * (1 / imageHeightToConstrainedHeightRatio), size.height);
}
return resultSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment