Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Created January 8, 2014 20:09
Show Gist options
  • Save isoiphone/8323683 to your computer and use it in GitHub Desktop.
Save isoiphone/8323683 to your computer and use it in GitHub Desktop.
Some functions are like recurring nightmares... I have this vague feeling I've written this many times before.
UIImage* aspectFitImage(UIImage* source, CGSize size)
{
const float wr = source.size.width/size.width;
const float hr = source.size.height/size.height;
const float scale = 1.0f/MIN(wr, hr);
const float width = ceilf(source.size.width*scale);
const float height = ceilf(source.size.height*scale);
CGRect rect = {(size.width-width)*0.5f, (size.height-height)*0.5f, width, height};
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[source drawInRect:rect];
UIImage* dest = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return dest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment