Reputation: 1343
This is the code I am using to convert the images to grayscale.
func convertToGrayScale(image: UIImage) -> UIImage
{
let imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
let colorSpace = CGColorSpaceCreateDeviceGray()
let width = image.size.width
let height = image.size.height
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue)
let context = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue)
CGContextDrawImage(context, imageRect, image.CGImage)
let imageRef = CGBitmapContextCreateImage(context)
let newImage = UIImage(CGImage: imageRef!)
return newImage
}
I don't want to see the black backgrounds. How can I fix it?
Edit: I've tried doing it with this code, it works, but now its takes 3 seconds for the images to load.
func convertToGrayScale(image: UIImage) -> UIImage {
let cgImage = image.CGImage!
let beginImage = CIImage(CGImage: cgImage)
let filter = CIFilter(name: "CIColorControls")!
filter.setValue(beginImage, forKey: kCIInputImageKey)
filter.setValue(0, forKey: kCIInputSaturationKey)
return UIImage(CIImage: filter.outputImage!)
}
Upvotes: 1
Views: 112
Reputation: 1343
This function solved my problem. It doesn't necessarily turn the images into grayscale but I was able to make it black for unknown recipes, dark gray for semi known & colored for known.
func createTintedImageFromImage(originalImage: UIImage, desiredColor: UIColor) -> UIImage {
let imageSize: CGSize = originalImage.size
let imageScale: CGFloat = originalImage.scale
let contextBounds: CGRect = CGRectMake(0, 0, imageSize.width, imageSize.height)
UIGraphicsBeginImageContextWithOptions(imageSize, false, imageScale)
UIColor.blackColor().setFill()
UIRectFill(contextBounds)
originalImage.drawAtPoint(CGPointZero)
let imageOverBlack: UIImage = UIGraphicsGetImageFromCurrentImageContext()
desiredColor.setFill()
UIRectFill(contextBounds)
imageOverBlack.drawAtPoint(CGPointZero, blendMode: .Multiply, alpha: 1)
originalImage.drawAtPoint(CGPointZero, blendMode: .DestinationIn, alpha: 1)
let finalImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage
}
Upvotes: 1