Skip to content

Instantly share code, notes, and snippets.

@Kirow
Forked from lanephillips/CGRectAspectFit.m
Created October 23, 2018 14:05
Show Gist options
  • Save Kirow/6e1f380b46a38c0d48f38cc6b0965721 to your computer and use it in GitHub Desktop.
Save Kirow/6e1f380b46a38c0d48f38cc6b0965721 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