Created
December 20, 2013 11:22
-
-
Save YGeorge/8053506 to your computer and use it in GitHub Desktop.
iOS scale image proportionally
DEFAULT_PHOTO_MAX_SIZE - max size (height or width) of new image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (UIImage *)scaleImageProportionally:(UIImage *)image { | |
if (MAX(image.size.height, image.size.width) <= DEFAULT_PHOTO_MAX_SIZE) { | |
return image; | |
} | |
else { | |
CGFloat targetWidth = 0; | |
CGFloat targetHeight = 0; | |
if (image.size.height > image.size.width) { | |
CGFloat ratio = image.size.height / image.size.width; | |
targetHeight = DEFAULT_PHOTO_MAX_SIZE; | |
targetWidth = roundf(DEFAULT_PHOTO_MAX_SIZE/ ratio); | |
} | |
else { | |
CGFloat ratio = image.size.width / image.size.height; | |
targetWidth = DEFAULT_PHOTO_MAX_SIZE; | |
targetHeight = roundf(DEFAULT_PHOTO_MAX_SIZE/ ratio); | |
} | |
CGSize targetSize = CGSizeMake(targetWidth, targetHeight); | |
UIImage *sourceImage = image; | |
UIImage *newImage = nil; | |
CGSize imageSize = sourceImage.size; | |
CGFloat width = imageSize.width; | |
CGFloat height = imageSize.height; | |
targetWidth = targetSize.width; | |
targetHeight = targetSize.height; | |
CGFloat scaleFactor = 0.0; | |
CGFloat scaledWidth = targetWidth; | |
CGFloat scaledHeight = targetHeight; | |
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0); | |
if (!CGSizeEqualToSize(imageSize, targetSize)) { | |
CGFloat widthFactor = targetWidth / width; | |
CGFloat heightFactor = targetHeight / height; | |
if (widthFactor < heightFactor) | |
scaleFactor = widthFactor; | |
else | |
scaleFactor = heightFactor; | |
scaledWidth = roundf(width * scaleFactor); | |
scaledHeight = roundf(height * scaleFactor); | |
// center the image | |
if (widthFactor < heightFactor) { | |
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; | |
} else if (widthFactor > heightFactor) { | |
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; | |
} | |
} | |
UIGraphicsBeginImageContext(targetSize); | |
CGRect thumbnailRect = CGRectZero; | |
thumbnailRect.origin = thumbnailPoint; | |
thumbnailRect.size.width = scaledWidth; | |
thumbnailRect.size.height = scaledHeight; | |
[sourceImage drawInRect:thumbnailRect]; | |
newImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
if (newImage == nil) NSLog(@"could not scale image"); | |
return newImage; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment