2015-01-23 00:02:08 +00:00
|
|
|
/// A `UIImage` extension that makes it easier to resize the image and inspect its size.
|
|
|
|
|
2014-12-12 20:29:17 +00:00
|
|
|
extension UIImage {
|
2015-01-23 00:02:08 +00:00
|
|
|
/// Resizes an image instance.
|
|
|
|
///
|
2015-06-09 21:28:11 +00:00
|
|
|
/// - parameter size: The new size of the image.
|
|
|
|
/// - returns: A new resized image instance.
|
2014-12-12 20:29:17 +00:00
|
|
|
func resize(size: CGSize) -> UIImage {
|
2015-04-23 22:30:57 +00:00
|
|
|
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
|
|
|
|
self.drawInRect(CGRect(origin: CGPointZero, size: size))
|
2014-12-12 20:29:17 +00:00
|
|
|
let newImage = UIGraphicsGetImageFromCurrentImageContext()
|
|
|
|
UIGraphicsEndImageContext()
|
2015-06-09 21:28:11 +00:00
|
|
|
return newImage ?? self
|
2014-12-12 20:29:17 +00:00
|
|
|
}
|
|
|
|
|
2015-04-23 22:30:57 +00:00
|
|
|
/// Resizes an image instance to fit inside a constraining size while keeping the aspect ratio.
|
|
|
|
///
|
2015-06-09 21:28:11 +00:00
|
|
|
/// - parameter size: The constraining size of the image.
|
|
|
|
/// - returns: A new resized image instance.
|
2015-04-23 22:30:57 +00:00
|
|
|
func resizeAspectFit(size: CGSize) -> UIImage {
|
|
|
|
let newSize = self.size.sizeConstrainedBySize(size)
|
|
|
|
return resize(newSize)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resizes an image instance to fill a constraining size while keeping the aspect ratio.
|
|
|
|
///
|
2015-06-09 21:28:11 +00:00
|
|
|
/// - parameter size: The constraining size of the image.
|
|
|
|
/// - returns: A new resized image instance.
|
2015-04-23 22:30:57 +00:00
|
|
|
func resizeAspectFill(size: CGSize) -> UIImage {
|
|
|
|
let newSize = self.size.sizeFillingSize(size)
|
|
|
|
return resize(newSize)
|
|
|
|
}
|
|
|
|
|
2015-01-23 00:02:08 +00:00
|
|
|
/// Returns a new `UIImage` instance using raw image data and a size.
|
|
|
|
///
|
2015-06-09 21:28:11 +00:00
|
|
|
/// - parameter data: Raw image data.
|
|
|
|
/// - parameter size: The size to be used to resize the new image instance.
|
|
|
|
/// - returns: A new image instance from the passed in data.
|
2014-12-12 20:29:17 +00:00
|
|
|
class func imageWithData(data: NSData, size: CGSize) -> UIImage? {
|
|
|
|
return UIImage(data: data)?.resize(size)
|
|
|
|
}
|
2014-12-12 21:49:22 +00:00
|
|
|
|
2015-01-23 00:02:08 +00:00
|
|
|
/// Returns an image size from raw image data.
|
|
|
|
///
|
2015-06-09 21:28:11 +00:00
|
|
|
/// - parameter data: Raw image data.
|
|
|
|
/// - returns: The size of the image contained in the data.
|
2014-12-12 20:29:17 +00:00
|
|
|
class func sizeForImageData(data: NSData) -> CGSize? {
|
|
|
|
return UIImage(data: data)?.size
|
|
|
|
}
|
|
|
|
}
|