Created
May 31, 2016 17:25
-
-
Save gregomni/91c5970230cecf3e0eaad4fe38d5d803 to your computer and use it in GitHub Desktop.
This file contains 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 characters
extension CGSize { | |
func scaled(byFactor: CGFloat) -> CGSize { | |
return CGSize(width: width*byFactor, height: height*byFactor) | |
} | |
} | |
extension UIImage { | |
static func drawnVia(size: CGSize, opaque: Bool = false, _ scale: CGFloat = 0.0, draw: () -> ()) -> UIImage { | |
UIGraphicsBeginImageContextWithOptions(size, opaque, scale) | |
draw() | |
let result = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return result! | |
} | |
} | |
func scaleAndCropImage(image: UIImage, toSize size: CGSize, fitImage: Bool = true) -> UIImage { | |
guard image.size != size else { return image } | |
// Calculate scale factor for fit or fill | |
let (widthFactor, heightFactor) = (size.width / image.size.width, size.height / image.size.height) | |
let scaleFactor = fitImage ? min(widthFactor, heightFactor) : max(widthFactor, heightFactor) | |
// Establish drawing destination, which may start outside the drawing context bounds | |
let scaledSize = image.size.scaled(scaleFactor) | |
let drawingOrigin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) | |
// Perform drawing and return image | |
return UIImage.drawnVia(size) { | |
UIColor.blackColor().setFill(); UIRectFill(CGRect(origin: .zero, size: size)) | |
image.drawInRect(CGRect(origin: drawingOrigin, size: scaledSize)) | |
} | |
} |
And:
func * (lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width * rhs, height: lhs.height * rhs) }
extension UIImage {
func scale(to destSize: CGSize, fitImage: Bool = true, backgroundColor: UIColor = .blackColor()) -> UIImage {
guard size != destSize else { return self }
// Establish drawing destination, which may start outside the drawing context bounds
let scaleFactor = (fitImage ? min : max)(destSize.width / size.width, destSize.height / size.height)
let scaledSize = size * scaleFactor
let drawingRect = CGRect(origin: .zero, size: scaledSize)
.offsetBy(dx: (destSize.width - scaledSize.width) / 2.0,
dy: (destSize.height - scaledSize.height) / 2.0)
// Perform drawing and return image
UIGraphicsBeginImageContextWithOptions(destSize, false, 0.0); defer { UIGraphicsEndImageContext() }
backgroundColor.setFill(); UIRectFill(CGRect(origin: .zero, size: destSize))
self.drawInRect(drawingRect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay, fine: