Skip to content

Instantly share code, notes, and snippets.

@kirel
Created August 11, 2009 15:59
Show Gist options
  • Select an option

  • Save kirel/165919 to your computer and use it in GitHub Desktop.

Select an option

Save kirel/165919 to your computer and use it in GitHub Desktop.
CGSize imageSize = image.size;
CGSize targetSize = CGSizeMake(36.0, 36.0);
CGFloat scaleFactor = 1.0;
CGFloat scaledWidth = imageSize.width;
CGFloat scaledHeight = imageSize.height;
CGPoint scaledOrigin = CGPointMake(0.0,0.0);
CGFloat widthFactor = targetSize.width / imageSize.width;
CGFloat heightFactor = targetSize.height / imageSize.height;
// only scale if larger than target
if ((image.size.width > targetSize.width) || (image.size.height > targetSize.height)) {
// compute scaling
if (widthFactor < heightFactor)
scaleFactor = widthFactor; // scale to fit height
else
scaleFactor = heightFactor; // scale to fit width
scaledWidth = imageSize.width * scaleFactor;
scaledHeight = imageSize.height * scaleFactor;
}
// center the image
if (targetSize.height > scaledHeight)
{
scaledOrigin.y = (targetSize.height - scaledHeight) * 0.5;
}
if (targetSize.width > scaledWidth)
{
scaledOrigin.x = (targetSize.width - scaledWidth) * 0.5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment