Last active
October 11, 2015 05:28
-
-
Save advantis/3810413 to your computer and use it in GitHub Desktop.
CGRect proportional scaling
This file contains 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 "tgmath.h" | |
CGRect ADVRectScaleToSize(CGRect sourceRect, CGSize targetSize, UIViewContentMode contentMode) | |
{ | |
CGSize sourceSize = sourceRect.size; | |
CGFloat horizontalRatio = targetSize.width / sourceSize.width; | |
CGFloat verticalRatio = targetSize.height / sourceSize.height; | |
CGFloat ratio; | |
switch (contentMode) | |
{ | |
case UIViewContentModeScaleAspectFit: | |
ratio = fmin(horizontalRatio, verticalRatio); | |
break; | |
case UIViewContentModeScaleAspectFill: | |
ratio = fmax(horizontalRatio, verticalRatio); | |
break; | |
// TODO: Implement other modes | |
default: | |
return sourceRect; | |
} | |
CGSize scaledSize = CGSizeMake(floor(ratio * sourceSize.width), | |
floor(ratio * sourceSize.height)); | |
sourceRect.origin.x += floor((targetSize.width - scaledSize.width) / 2.f); | |
sourceRect.origin.y += floor((targetSize.height - scaledSize.height) / 2.f); | |
sourceRect.size = scaledSize; | |
return sourceRect; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment