Skip to content

Instantly share code, notes, and snippets.

@justin
Created February 18, 2013 19:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justin/4979919 to your computer and use it in GitHub Desktop.
Save justin/4979919 to your computer and use it in GitHub Desktop.
Category to get the frame of an image that's inside a UIImageView. Since I use aspect fit on some stuff, I sometimes need to account for the top and bottom borders.
#import <UIKit/UIKit.h>
@interface UIImageView (SGExtensions)
- (CGRect)sg_imageFrame;
@end
#import "UIImageView+SGExtensions.h"
@implementation UIImageView (SGExtensions)
- (CGRect)sg_imageFrame
{
CGSize imageSize = self.image.size;
CGSize frameSize = self.frame.size;
CGRect resultFrame = CGRectZero;
BOOL imageSmallerThanFrame = (imageSize.width < frameSize.width) && (imageSize.height < frameSize.height);
if (imageSmallerThanFrame == YES)
{
resultFrame.size = imageSize;
}
else
{
CGFloat widthRatio = roundf(imageSize.width / frameSize.width);
CGFloat heightRatio = roundf(imageSize.height / frameSize.height);
CGFloat maxRatio = MAX(widthRatio, heightRatio);
resultFrame.size = (CGSize){ roundf(imageSize.width / maxRatio), roundf(imageSize.height / maxRatio) };
}
resultFrame.origin = (CGPoint) {roundf(self.center.x - resultFrame.size.width / 2), roundf(self.center.y - resultFrame.size.height / 2) };
return resultFrame;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment