Last active
October 10, 2017 01:12
-
-
Save jeffaburt/eb3a99ea5ce64ac62401832fbba61461 to your computer and use it in GitHub Desktop.
Revisions
-
jeffaburt revised this gist
Oct 10, 2017 . 1 changed file with 3 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,3 +1,5 @@ import UIKit extension UIImage { /** Returns a new UIImage instance by applying the new size. @@ -53,7 +55,7 @@ extension UIImage { UIGraphicsEndImageContext() if newImage == nil { print("Could not scale image to size: \(targetSize.debugDescription)") } return newImage! -
jeffaburt created this gist
Oct 10, 2017 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ extension UIImage { /** Returns a new UIImage instance by applying the new size. - discussion: http://stackoverflow.com/a/2025413/1926015 - parameter targetSize: the new size - returns: a UIImage with the new size */ func imageByScalingProportionallyToSize(_ targetSize: CGSize) -> UIImage { let sourceImage = self var newImage: UIImage? let imageSize = sourceImage.size let width = imageSize.width let height = imageSize.height let targetWidth = targetSize.width let targetHeight = targetSize.height var scaleFactor = CGFloat(0) var scaledWidth = targetWidth var scaledHeight = targetHeight var thumbnailPoint = CGPoint(x: 0.0, y: 0.0) if !imageSize.equalTo(targetSize) { let widthFactor = targetWidth / width let heightFactor = targetHeight / height if widthFactor < heightFactor { scaleFactor = widthFactor } else { scaleFactor = heightFactor } scaledWidth = width * scaleFactor scaledHeight = height * scaleFactor // center the image if widthFactor < heightFactor { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5 } else if widthFactor > heightFactor { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5 } } // this is actually the interesting part: UIGraphicsBeginImageContextWithOptions(targetSize, false, 0) var thumbnailRect: CGRect = .zero thumbnailRect.origin = thumbnailPoint thumbnailRect.size.width = scaledWidth thumbnailRect.size.height = scaledHeight sourceImage.draw(in: thumbnailRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if newImage == nil { DDLogWarn("Could not scale image to size: \(targetSize.debugDescription)") } return newImage! } }