From f57f725147e7b338d97e89fdf628a5fa39e6555e Mon Sep 17 00:00:00 2001 From: Tony DiPasquale Date: Thu, 23 Apr 2015 18:15:19 -0400 Subject: [PATCH] Resize image keeping aspect ratio --- Source/UIImageExtension.swift | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Source/UIImageExtension.swift b/Source/UIImageExtension.swift index dfa82f8..e68e4da 100644 --- a/Source/UIImageExtension.swift +++ b/Source/UIImageExtension.swift @@ -6,8 +6,9 @@ extension UIImage { /// :param: size The new size of the image. /// :returns: A new resized image instance. func resize(size: CGSize) -> UIImage { - UIGraphicsBeginImageContext(size) - self.drawInRect(CGRectMake(0, 0, size.width, size.height)) + let newSize = self.size.sizeConstrainedBySize(size) + UIGraphicsBeginImageContext(newSize) + self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage @@ -30,3 +31,23 @@ extension UIImage { return UIImage(data: data)?.size } } + +private extension CGSize { + /// Finds a new size constrained by a size keeping the aspect ratio. + /// + /// :param: size The contraining size. + /// :returns: size A new size that fits inside the contraining size with the same aspect ratio. + func sizeConstrainedBySize(size: CGSize) -> CGSize { + if height == 0 { return size } + + let aspectRatio = width / height + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + if aspectWidth > size.width { + return CGSize(width: size.width, height: aspectHeight) + } else { + return CGSize(width: aspectWidth, height: size.height) + } + } +}