Created
February 18, 2013 19:27
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface UIImageView (SGExtensions) | |
- (CGRect)sg_imageFrame; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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