The iPhone app I'm working on in my spare time lets the user capture photos as part of its functionality. After I receive the image, I need to resize it so that it's a thumbnail size.
To make this easier, I've written a UIImage Swift extension that provides you two functions: scaleToMaxSize()
scales an image to the maximum size specified, scaleToSize()
scales the image to exactly the specified size. scaleToMaxSize()
works in conjunction with scaleToSize()
.
//
// UIImage+CKScaling.swift
// BlackBook
//
// Created by Corey Klass on 2/28/16.
// Copyright © 2016 Corey Klass. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
func scaleToMaxSize(maxSize: CGSize) -> UIImage {
// get the scale values for the width and height
let xScale = maxSize.width / self.size.width
let yScale = maxSize.height / self.size.height
// we'll need one of these scales, whichever fits
let xScaleSize = CGSizeMake(self.size.width * xScale, self.size.height * xScale)
let yScaleSize = CGSizeMake(self.size.width * yScale, self.size.height * yScale)
var newSize: CGSize
// if the x scale is too large, use the y scale
if ((xScaleSize.width > maxSize.width) || (xScaleSize.height > maxSize.height)) {
newSize = yScaleSize
}
// otherwise use the x scale
else {
newSize = xScaleSize
}
// resize and return the image
let image = self.scaleToSize(newSize)
return image
}
func scaleToSize(size: CGSize) -> UIImage {
// Create a bitmap graphics context
// This will also set it as the current context
UIGraphicsBeginImageContext(size)
// Draw the scaled image in the current context
self.drawInRect(CGRectMake(0.0, 0.0, size.width, size.height))
// Create a new image from current context
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
// Pop the current context from the stack
UIGraphicsEndImageContext()
// Return our new scaled image
return scaledImage
}
}