Skip to content

Instantly share code, notes, and snippets.

@advantis
Last active October 11, 2015 05:28
Show Gist options
  • Save advantis/3810413 to your computer and use it in GitHub Desktop.
Save advantis/3810413 to your computer and use it in GitHub Desktop.
CGRect proportional scaling
#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