From a9963e3b01010a9e9d56c597d27a955fa7dec3a0 Mon Sep 17 00:00:00 2001 From: Tony DiPasquale Date: Thu, 23 Apr 2015 18:30:57 -0400 Subject: [PATCH] Add aspect fill and fit as separate functions --- Source/UIImageExtension.swift | 41 ++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/Source/UIImageExtension.swift b/Source/UIImageExtension.swift index e68e4da..870833f 100644 --- a/Source/UIImageExtension.swift +++ b/Source/UIImageExtension.swift @@ -6,14 +6,31 @@ extension UIImage { /// :param: size The new size of the image. /// :returns: A new resized image instance. func resize(size: CGSize) -> UIImage { - let newSize = self.size.sizeConstrainedBySize(size) - UIGraphicsBeginImageContext(newSize) - self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) + UIGraphicsBeginImageContextWithOptions(size, false, 0.0) + self.drawInRect(CGRect(origin: CGPointZero, size: size)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } + /// Resizes an image instance to fit inside a constraining size while keeping the aspect ratio. + /// + /// :param: size The constraining size of the image. + /// :returns: A new resized image instance. + func resizeAspectFit(size: CGSize) -> UIImage { + let newSize = self.size.sizeConstrainedBySize(size) + return resize(newSize) + } + + /// Resizes an image instance to fill a constraining size while keeping the aspect ratio. + /// + /// :param: size The constraining size of the image. + /// :returns: A new resized image instance. + func resizeAspectFill(size: CGSize) -> UIImage { + let newSize = self.size.sizeFillingSize(size) + return resize(newSize) + } + /// Returns a new `UIImage` instance using raw image data and a size. /// /// :param: data Raw image data. @@ -50,4 +67,22 @@ private extension CGSize { return CGSize(width: aspectWidth, height: size.height) } } + + /// Finds a new size filling the given size while keeping the aspect ratio. + /// + /// :param: size The contraining size. + /// :returns: size A new size that fills the contraining size keeping the same aspect ratio. + func sizeFillingSize(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: aspectWidth, height: size.height) + } else { + return CGSize(width: size.width, height: aspectHeight) + } + } }