Skip to content

Instantly share code, notes, and snippets.

@vladimirgoncharov
Last active September 6, 2015 11:12
Show Gist options
  • Save vladimirgoncharov/5a30d396752699aa5fcf to your computer and use it in GitHub Desktop.
Save vladimirgoncharov/5a30d396752699aa5fcf to your computer and use it in GitHub Desktop.
Resize image via CGBitmap
extension UIImage {
func resize(size: CGSize) -> UIImage! {
if let colorSpace = CGColorSpaceCreateDeviceRGB() {
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, 0, colorSpace, bitmapInfo.rawValue)
CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height))
switch self.imageOrientation
{
case .Up, .UpMirrored:
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage)
case .Left, .LeftMirrored:
CGContextRotateCTM(context, CGFloat(M_PI_2))
CGContextTranslateCTM(context, 0.0, -size.width)
CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage)
case .Right, .RightMirrored:
CGContextRotateCTM(context, CGFloat(-M_PI_2))
CGContextTranslateCTM(context, -size.height, 0.0)
CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage)
case .Down, .DownMirrored:
CGContextRotateCTM(context, CGFloat(M_PI));
CGContextTranslateCTM(context, -size.width, -size.height)
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage)
}
if let scaledImage = CGBitmapContextCreateImage(context) {
return UIImage(CGImage: scaledImage)
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment