Skip to content

Instantly share code, notes, and snippets.

@romainmenke
Last active November 20, 2016 11:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainmenke/67066cf20c680cd7d4c3156ae903d0b1 to your computer and use it in GitHub Desktop.
Save romainmenke/67066cf20c680cd7d4c3156ae903d0b1 to your computer and use it in GitHub Desktop.
import UIKit
// Swift rewrite challenge
// Starting point: https://gist.github.com/jkereako/200342b66b5416fd715a#file-scale-and-crop-image-swift
extension CGSize {
func scale(toSize newSize: CGSize, fit: Bool) -> CGSize {
let test : (CGFloat,CGFloat) -> CGFloat = fit ? { max($0, $1) } : { min($0, $1) }
let scale : CGFloat = test(width / newSize.width, height / newSize.height)
return CGSize(width: (width / scale), height: (height / scale))
}
}
extension UIImage {
func scale(toSize newSize:CGSize, fit:Bool) -> UIImage {
guard size != newSize else { return self }
let scaledSize = size.scale(toSize: newSize, fit: fit)
let drawingOrigin = CGPoint(x: (newSize.width - scaledSize.width) / 2.0,y: (newSize.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
defer { UIGraphicsEndImageContext() }
UIColor.blackColor().setFill()
UIRectFill(CGRect(origin: .zero, size: newSize))
drawInRect(CGRect(origin: drawingOrigin, size: scaledSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
// Test with some basic placeholder data
guard let url = NSURL(string: "http://placehold.it/300x150") else { fatalError("Bad URL") }
guard let data = NSData(contentsOfURL: url) else { fatalError("Bad data") }
guard let img = UIImage(data: data) else { fatalError("Bad data") }
let outImageFit = img.scale(toSize: CGSize(width: 200, height: 200), fit: true)
let outImageFill = img.scale(toSize: CGSize(width: 200, height: 200), fit: false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment