Swift:UIGraphics Scale Down CGImage

From Hawk Wiki
Jump to: navigation, search
func scaleDownCGImage(image: CGImage, scale: Float) -> CGImage!{
    var scaleDiv = UInt(1.0 / scale)
    let width = CGImageGetWidth(image) / scaleDiv
    let height = CGImageGetHeight(image) / scaleDiv
    let bitsPerComponent = CGImageGetBitsPerComponent(image)
    let bytesPerRow = CGImageGetBytesPerRow(image)
    let colorSpace = CGImageGetColorSpace(image)
    let bitmapInfo = CGImageGetBitmapInfo(image)
    let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
    CGContextSetInterpolationQuality(context, kCGInterpolationMedium)
    let imgSize = CGSize(width: Int(width), height: Int(height))
    CGContextDrawImage(context, CGRect(origin: CGPointZero, size: imgSize), image)
    return CGBitmapContextCreateImage(context)
}