Skip to content

Instantly share code, notes, and snippets.

@wildthink
Forked from lanephillips/CGRectAspectFit.m
Created March 22, 2017 17:15
Show Gist options
  • Save wildthink/d7cdd6394b1b3add915945ef76543821 to your computer and use it in GitHub Desktop.
Save wildthink/d7cdd6394b1b3add915945ef76543821 to your computer and use it in GitHub Desktop.
Objective-C code to fit a CGRect inside or outside another CGRect while maintaining aspect ratio. The fitted rectangle is centered on the target rectangle.
CGFloat ScaleToAspectFitRectInRect(CGRect rfit, CGRect rtarget)
{
// first try to match width
CGFloat s = CGRectGetWidth(rtarget) / CGRectGetWidth(rfit);
// if we scale the height to make the widths equal, does it still fit?
if (CGRectGetHeight(rfit) * s <= CGRectGetHeight(rtarget)) {
return s;
}
// no, match height instead
return CGRectGetHeight(rtarget) / CGRectGetHeight(rfit);
}
CGRect AspectFitRectInRect(CGRect rfit, CGRect rtarget)
{
CGFloat s = ScaleToAspectFitRectInRect(rfit, rtarget);
CGFloat w = CGRectGetWidth(rfit) * s;
CGFloat h = CGRectGetHeight(rfit) * s;
CGFloat x = CGRectGetMidX(rtarget) - w / 2;
CGFloat y = CGRectGetMidY(rtarget) - h / 2;
return CGRectMake(x, y, w, h);
}
CGFloat ScaleToAspectFitRectAroundRect(CGRect rfit, CGRect rtarget)
{
// fit in the target inside the rectangle instead, and take the reciprocal
return 1 / ScaleToAspectFitRectInRect(rtarget, rfit);
}
CGRect AspectFitRectAroundRect(CGRect rfit, CGRect rtarget)
{
CGFloat s = ScaleToAspectFitRectAroundRect(rfit, rtarget);
CGFloat w = CGRectGetWidth(rfit) * s;
CGFloat h = CGRectGetHeight(rfit) * s;
CGFloat x = CGRectGetMidX(rtarget) - w / 2;
CGFloat y = CGRectGetMidY(rtarget) - h / 2;
return CGRectMake(x, y, w, h);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment