Swift версия, проверенная и работающая на 100%:
func imageToGreyImage(image: UIImage) -> UIImage {
// Create image rectangle with current image width/height
var actualWidth = image.size.width;
var actualHeight = image.size.height;
var imageRect = CGRectMake(0, 0, actualWidth, actualHeight);
var colorSpace = CGColorSpaceCreateDeviceGray();
var bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.None.rawValue)
var context = CGBitmapContextCreate(nil, Int(actualWidth), Int(actualHeight), 8, 0, colorSpace, bitmapInfo);
CGContextDrawImage(context, imageRect, image.CGImage);
var grayImage = CGBitmapContextCreateImage(context);
bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.Only.rawValue)
context = CGBitmapContextCreate(nil, Int(actualWidth), Int(actualHeight), 8, 0, nil, bitmapInfo);
CGContextDrawImage(context, imageRect, image.CGImage);
var mask = CGBitmapContextCreateImage(context);
var grayScaleImage = UIImage(CGImage: CGImageCreateWithMask(grayImage, mask), scale: image.scale, orientation: image.imageOrientation)
// Return the new grayscale image
return grayScaleImage!;
}
А если вы не хотите альфа, просто удалите следующую строку:
bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.Only.rawValue)