Skip to content

Instantly share code, notes, and snippets.

@jeffaburt
Last active October 10, 2017 01:12
Show Gist options
  • Save jeffaburt/eb3a99ea5ce64ac62401832fbba61461 to your computer and use it in GitHub Desktop.
Save jeffaburt/eb3a99ea5ce64ac62401832fbba61461 to your computer and use it in GitHub Desktop.
imageByScalingProportionallyToSize
import UIKit
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 {
print("Could not scale image to size: \(targetSize.debugDescription)")
}
return newImage!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment